Reputation: 2542
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?
Upvotes: 2
Views: 128
Reputation: 68715
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 i.e. Child
and hence Child method is called.
Upvotes: 2
Reputation: 5577
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");
}
Upvotes: 1
Reputation: 62583
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
.
Upvotes: 1