I have two classes, Parent (superclass) and Child (subclass).
public class Parent(){
public void hello(){
System.out.println("HelloParent");
bye();
}
public void bye(){
System.out.println("ByeParent");
}
}
public class Child extends Parent(){
@Override
public void hello(){
super.hello();
}
@Override
public void bye(){
System.out.println("ByeChild");
}
}
If I create a Child
instance and invoke its hello()
method, it invokes the Child
's hello
method, and not the Parent
's hello
method.
Child c = new Child();
c.hello();
Output:
"HelloParent"
"ByeChild"
But why is it not "ByeParent"?
Why doesn't it invoke the superclass's method?
Any instance method call will happen on the object the instance belong to no matter where the code is. So while executing this code:
public void hello(){
System.out.println("HelloParent");
bye();
}
bye
method will be called on the the calling object ie Child
and hence Child method is called.
Well, that is how polymorphism works in OO. Since the instance you are working with is Child
, it is no surprise that Child.bye()
was invoked!
If you really wanted it to print ByeParent
, then you'd have to write the bye()
in Child
as follows:
@Override
public void bye(){
super.bye();
System.out.println("ByeChild");
}
Note that you could've also done this:
Parent obj = new Child();
obj.hello();
However, even in this case, it would still print ByeChild
.
Overriding a method replaces it completely, it doesn't add on to it. If you also want to call the original method, you need to call it explicitly using the keyword "super":
@Override
public void bye(){
super.bye();
System.out.println("ByeChild");
}
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.