继承和递归 [英] Inheritance and recursion

查看:120
本文介绍了继承和递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下类:

class A {

    void recursive(int i) {
        System.out.println("A.recursive(" + i + ")");
        if (i > 0) {
            recursive(i - 1);
        }
    }

}

class B extends A {

    void recursive(int i) {
        System.out.println("B.recursive(" + i + ")");
        super.recursive(i + 1);
    }

}

现在我们可以拨打在A类递归

public class Demo {

    public static void main(String[] args) {
        A a = new A();
        a.recursive(10);
    }

}

按预期计算输出从10开始。

The output is, as expected counting down from 10.

A.recursive(10)
A.recursive(9)
A.recursive(8)
A.recursive(7)
A.recursive(6)
A.recursive(5)
A.recursive(4)
A.recursive(3)
A.recursive(2)
A.recursive(1)
A.recursive(0)

让我们来看看令人困惑的部分。现在我们在B类中调用递归

Let's get to the the confusing part. Now we call recursive in class B.

预期

B.recursive(10)
A.recursive(11)
A.recursive(10)
A.recursive(9)
A.recursive(8)
A.recursive(7)
A.recursive(6)
A.recursive(5)
A.recursive(4)
A.recursive(3)
A.recursive(2)
A.recursive(1)
A.recursive(0)

实际

B.recursive(10)
A.recursive(11)
B.recursive(10)
A.recursive(11)
B.recursive(10)
A.recursive(11)
B.recursive(10)
..infinite loop...

这是怎么发生的?我知道这是一个设计的例子,但它让我很奇怪。

How does this happen? I know this is a devised example, but it makes me wonder.

老问题具体用例

推荐答案

这是预期。对于 B 的实例会发生这种情况。

This is expected. This is what happens for an instance of B.

class A {

    void recursive(int i) { // <-- 3. this gets called
        System.out.println("A.recursive(" + i + ")");
        if (i > 0) {
            recursive(i - 1); // <-- 4. this calls the overriden "recursive" method in class B, going back to 1.
        }
    }

}

class B extends A {

    void recursive(int i) { // <-- 1. this gets called
        System.out.println("B.recursive(" + i + ")");
        super.recursive(i + 1); // <-- 2. this calls the "recursive" method of the parent class
    }

}

因此,这些电话在 A B 之间交替。

As such, the calls are alternating between A and B.

A 的实例中不会发生这种情况,因为不会调用overriden方法。

This doesn't happen in the case of an instance of A because the overriden method won't be called.

这篇关于继承和递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆