Why does the program print the height value 0 instead of the one I set?

struct_dhancha :

I am confused about how are the methods and constructors called at runtime, since the derived constructor is printed 3 times and the height is printed 0

I have tried printing some messages inside methods and constructors as to know what exactly is happening

public class Derived extends Base{
    public static void main(String args[]){
        System.out.println("Hello World");
        Derived d = new Derived();
    }

    protected Derived(){
        System.out.println("Inside Derived Const");
        showAll();
    }

    protected void showAll(){
        System.out.println("Inside Derived showAll");
        System.out.println(getClass().getName()+" : "+height);
    }

    double height = 106.0;
}

class Base{

    protected Base(){
        System.out.println("Inside Base Const");
        showAll();
    }

    protected void showAll(){
        System.out.println("Inside Base showAll");
        System.out.println(getClass().getName()+" : "+height);
    }

    double height = 196.0;
}

I expected the output to be

Hello world
Derived : 106
Base : 196

instead I am getting

Hello World
Inside Base Const
Inside Derived showAll
Derived : 0.0
Inside Derived Const
Inside Derived showAll
Derived : 106.0
ישו אוהב אותך :

It's because you derived the Derived class from Base class and shadowing the variable and also overriding the methods.

You're calling the constructor of the Base class whenever you're instantiating the Derived class with:

Derived d = new Derived();

Here what happens when you're calling the above code:

  • Constructor of Base class Base() is called,
  • then "Inside Base Const" is printed,
  • method showAll() is not called because it's being override. Method showAll() inside the Derived class is called instead,
  • "Inside Base showAll" is printed,
  • "Derived : 106.0" is printed because double height = 196.0; inside Base class is being shadowed by double height = 106.0; inside the Derived class.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=124513&siteId=1