-8

// 我得到了错误的答案,但每次我再次追踪时,我都会得到相同的答案。我不明白为什么它打印设置四次。

public class A{ 
           public int number; 
           public A(){ 
             setNumber(0); 
           } 
           public void setNumber(int d){
             number = d;
           }
           public String toString(){ 
             return number+":I am A";
           }
        }



        public class B extends A{
         public B(){ 
             super(); 
         } 
         public void setNumber(int d){ 
             System.out.println("Setting"); 
             number = d; 
         } 
         public String toString(){
           return super.toString()+" - I am B"; 
         }
        }


        //AND THIS IS THE MAIN METHOD

        public class C{
            public static void main(String[] args){
                A one = new A();
                B two = new B(); //no empty constructor
                A three = new B();
                three.setNumber(5);
                two.setNumber(3);
                one.setNumber(1);
                System.out.println(three);
                System.out.println(two);
                System.out.println(one);
            }

      //  THIS IS MY ANSWER:
        Setting
        Setting
        5:I am A - I am B
        3:I am A - I am B
        1:I am A

这是正确的答案:我不明白为什么它打印设置超过两次设置设置设置设置 5:我是 A 3:我是 A - 我是 B 1:我是 A

      //  THANKS GUYS FOR YOUR HELP!!!!
4

1 回答 1

2

额外的两个settingB's 的构造函数打印。B的构造函数调用A' 构造函数,然后调用B'重写 SetNumber的Function 打印settingB的构造函数被调用了两次,而 SetNumber 被直接调用了两次,导致了 4 次Settings

于 2013-04-13T15:25:37.417 回答