首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

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

2012-01-26 
不解,为什么这个结果iJava codepublic class work2 {public static void main(String[] args){father Ane

不解,为什么这个结果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;    }} 

热点排行