Hello!!!. So in a quiz que were given the following classes and we were asked to give the output. [closed]

Tag: polymorphism Author: zhoukai30268 Date: 2013-03-28

// I GOT THE WRONG ANSWER, BUT EVERY TIME I TRACED AGAIN I GET THE SAME ANSWER. I DO NOT UNDERSTAND WHY IT PRINTS SETTING FOUR TIMES.

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

AND THIS IS THE CORRECT ANSWER:I DO NOT UNDERSTAND WHY IT PRINTS SETTING MORE THAN TWO TIMES Setting Setting Setting Setting 5:I am A 3:I am A - I am B 1:I am A

      //  THANKS GUYS FOR YOUR HELP!!!!
Please don't shout. It will take some time to clean up.
You seem to misunderstand what Stack Overflow is - we are not a site where we will do your work for you. You need to make an effort first - show us this effort and explain exactly where you are stuck. We can help with that.
sorry for not being clear but I do not think you understood my question. This is not a Homework. This was a question from a test that I took weeks ago. It seems like you did not read till the endThanks for your time anyways.

Best Answer

The two additional setting are printed by B's constructor. B's constructor calls A's constructor which then calls B's overridden SetNumber Function which prints setting. B's constructor is called twice and SetNumber is called directly twice leading to four Settings.