Suppose you have 3 Java classes: A, B, and C. Class B extends A, and class C extends B. Think of the class inheritance hierarchy alphabetically – with A at the top, then B in the middle, and finally C on the bottom. All 3 classes implement the instance method void doIt(). A reference variable is instantiated as "A x = new B();" and then x.doIt() is executed. What version of the doIt() method is actually executed and why? |
|
Yikes! This a long question, and could be confusing when you see it the first time – but it’s really not that bad at all. The best way to solve something like this is to write out the actual code. With that in mind here is what the Java code would look like:
class A
{
public doIt( )
{
//this does something
}
}
class B extends A
{
public doIt( )
{
//this does something
}
}
class C extends B
{
public doIt( )
{
//this does something
}
}
public static void main(String[] args) {
// this is a legal Java statement:
A x = new B( );
/*
What version of the doIt( ) method
will get executed by the statement below
- the one that belongs to class A, B, or C?
*/
x.doIt( );
}
So, given the code above the question is which version of the doIt( ) method will be executed – the one in class A, B, or C? The statement that causes a lot of confusion is the “A x = new B();” statement. What exactly is going on here? Well, although the variable x is an object of type A, it is instantiated as an object of class B – because of the “= new B( );” part of the statement. The Java runtime will basically look at this statement and say “even though x is clearly declared as type A, it is instantiated as an object of class B, so I will run the version of the doIt() method that is defined in class B.” So, what is dynamic binding?The version of the doIt() method that’s executed by the object x is the one in class B because of dynamic binding in Java. Dynamic binding basically means that the method implementation that is actually called is determined at run-time, and not at compile-time. And that’s why it’s called dynamic binding – because the method that will be run is chosen at run time. Dynamic binding is also known as late binding. |
Subscribe to our newsletter for more free interview questions.
Follow @programmerintvwVaroon Sahgal, Author of ProgrammerInterviewon

