Reputation: 75
I have come across a question recently on multilevel inheritance in java, the question is as follows :
public class Test{
public static void main(String[] args) {
A c = new C();
c.print();
}
}
class A{
public void print(){
System.out.println("Inside A");
}
}
class B extends A{
@Override
public void print(){
System.out.println("Inside B");
}
}
class C extends B{
}
So my question is why this is printing as "Inside B". Because class C is not overriding the method print() and hence it should resolve the method based on compile time and hence should print "Inside A". Please let me know if I'm missing anything. Thank you for your help.
Upvotes: 0
Views: 267
Reputation: 634
By the laws of inheritance in Java, all functions in the base class are used by derived classes including ones that are overridden. Any class that inherits from an intermediately inherited class will take the overridden definition. This is self-evident as these overridden functions override any function definition before it in the inheritance hierarchy. Therefore, the overridden function acts as a base class definition of any derived class underneath it.
Upvotes: 1
Reputation: 334
c
is of type A
, but the A
itself was initialised as instance of C
, and since C
extends B
and B
overrides A
, the both B
and C
override method inside A
. But since C
does not override B
, the method used is from B.
Got to say, that is pretty neat brain exercise.
Upvotes: 1
Reputation: 37655
You are confusing two things.
If a method is overridden one or more times, the version in the most specific subclass will run. That is why the version in B
is the one used.
On the other hand, when choosing between overloaded methods, the decision is based on the compile time type of the arguments.
Upvotes: 1
Reputation: 10988
C extends B, which means that it will have the same methods as B and it this case B has overridden the method, thus C will also have it.
Upvotes: 5
Reputation: 4638
It's printing "Inside B" because that is the class that C is extending, and B is thus C's superclass.
Upvotes: 1