Java subclass method when trying to use parent class method

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 are there some reasons for this behavior?

+7
source share
8 answers

No, this is correct (this is due to polymorphism). All method calls work with the object, not the link type.

Here your object is of type B, so a class B testing method will be issued.

+3
source

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

How wikipedia does it nicely:

The main use of polymorphism in industry (an object-oriented programming theory) is the ability of objects of different types to respond to calls to a method, field or property with the same name, each of which corresponds to a corresponding type of behavior. the programmer (and the program) does not need to know the exact type of object in advance, and therefore the exact behavior is determined at runtime (this is called length binding or dynamic binding).

+5
source

This is polymorphism and more specifically in Java redefinition . If you want to call a class A method from class B, you need to use super to call the superclass method. eg:

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

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

0
source

For

 A a1 = new B(); 

a1 points to an object B, which is a real type at runtime. Therefore, the value is inferred from object B.

0
source
 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 can make things easier to understand.

0
source

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

0
source

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

0
source

All Articles