Java calling subclass method when trying to use parent class method

最后都变了- 提交于 2021-02-04 17:41:07

问题


If I have two classes, A and B,

public class A {
    public int test() {
        return 1;
    }
}

public class B extends A{
    public int test() {
        return 2;
    }
}

If I do: A a1 = new B(), then a1.test() returns 2 instead of 1 as desired. Is this just a quirk of Java, or is there some reason for this behavior?


回答1:


No, that is correct (it is due to polymorphism). All method calls operate on object, not reference type.

Here your object is of type B, so test method of class B will be called.




回答2:


This is called polymorphism. At runtime the correct method will be called according to the "real" type of a1, which is B in this case.

As wikipedia puts it nicely:

The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run-time (this is called late binding or dynamic binding).




回答3:


This is polymorphism and more specifically in Java overriding. If you want to invoke Class A's test method from Class B then you need to use super to invoke the super classes method. e.g:

public class B extends A{
   public int test() {
       return super.test();
}



回答4:


This is intended behavior. The method test() in class B is overriding the method test() of class A.




回答5:


For

A a1 = new B();

a1 is pointing towards the object of B which is the real type at run-time. Hence value is printed from Object B.




回答6:


A obj = new A();
obj.test()

will return 1

A obj = new B();
obj.test()

will return 2

B obj = new B();
obj.test()

will return 2

As stated in other answers this is how polymorphism works.

This post may make things a bit clearer




回答7:


Java uses dynamic binding (or late binding), so the method of B is called, not A. This is the opposite of static binding. There is a nice example here.




回答8:


You declare your object as A but your instance is B. So the method which will be called is from class B. B extends A(we can say that A is parent for B) if you will comment method test in B and then recall this method, in this case the method invoked will be test from A class and will return 1.



来源:https://stackoverflow.com/questions/12266744/java-calling-subclass-method-when-trying-to-use-parent-class-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!