简体   繁体   English

使用引用变量的方法调用

[英]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. 问题---->为什么当控制权交给基类构造函数时,将调用派生类的setVar()方法而不是基类setVar()方法。 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. 我期望输出为30,但是当在调试模式下运行该程序时,发现该流并获得了40的输出。任何人都可以解释其背后的逻辑。 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. Java将根据变量的运行时类型(即始终使用多态)来决定要运行哪种方法,即使调用的方法来自基类构造函数也是如此。

When the base class constructor is called, polymorphism means that the derived class's version of setVar is called, and 20 is added. 调用基类构造函数时,多态意味着调用派生类的setVar版本,并添加20。 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. 然后,调用派生类的构造函数,并再次调用派生类的setVar版本,并再次添加20,得到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. 因此, Derived setVar()被调用了两次,因为它在“ Derived ”中被覆盖,并且您尝试创建“ Derived ”类的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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