简体   繁体   中英

Method calling using reference variable

public class Base {

    int var =0;
    Base(){
        System.out.println("Inside Base constructor .....");
        setVar();
    }

    public void setVar(){
        System.out.println("Inside base setVar method.....");
        var+=10;
    }

    public int getVar(){
        return var;
    }
}

Derived Class:

public class Derived extends Base {

    Derived(){
        System.out.println("Inside Derived constructor .....");
        setVar();
    }

    public void setVar(){
        System.out.println("Inside Derived setVar method.....");

        var+=20;
    }

    public static void main(String[] args){

        Base b = new Derived();
        System.out.println(b.getVar());
    }
}

Output.....

Inside Base constructor .....                                                      
Inside Derived setVar method.....                                                   
Inside Derived constructor .....                                                    
Inside Derived setVar method.....                                                   
40

Question ----> why when control goes to base class constructor , setVar() method of Derived class is called instead of Base class setVar() method. I expected output as 30 , but when ran this program in debug mode found the flow and got output as 40. Could anyone please explain the logic behind this. Thanks

Java will decide which method to run based on the runtime type of the variable, ie use polymorphism, at all times, even if the method called is from a base class constructor.

When the base class constructor is called, polymorphism means that the derived class's version of setVar is called, and 20 is added. Then the derived class constructor is called, and again the derived class's version of setVar is called, and 20 is added, again, yielding 40.

Polymorphism at work.

When you override a super class method in derived class, then always your overridden method in derived class is called when someone operates on any object of derived class, even if that someone is a super class.

so Derived setVar() is called twice because it is overridden in ' Derived ' and you tried to create an object of ' Derived ' class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM