读书人

不解,为什么这个结果i解决方法

发布时间: 2012-01-26 19:40:46 作者: rapoo

不解,为什么这个结果i

Java code
public class work2 {    public static void main(String[] args){        father A=new father();        son C=new son();        System.out.println("A="+C.f());    }}class father{    int i=1;    public int f(){        if(i==4)            return 0;        System.out.println(i+++"father");        return f();    }}class son extends father{    static int j=1;    public int f(){        System.out.println(j+++"son="+super.f());        return 0;    }}



[解决办法]
我估计你对 return f(); 这个没有看清。

这个返回时,并不是调用father的函数,不是自己调自己,而是运行的是son的的f().

因为C就是son, 只要重名的,被override的都是调用子类的。


[解决办法]
Java code
public class work2 {    public static void main(String[] args){       // father A=new father();  delete        son C=new son();        System.out.println("A="+C.f());    }}class father{    int i=1;    public int f(){        if(i==4)            return 0;        System.out.println(i+++"father");        return f();//这里做递归调用  f()调用的 是son里面的 f()     }}class son extends father{    static int j=1;    public int f(){        System.out.println(j+++"son="+super.f());        return 0;    }} 

读书人网 >J2SE开发

热点推荐