Home           J2EE Concepts           JMS           Java Language           Contact           Back           Next           Bookmark this Page          










Some useful tips related to:
 - health & fitness
 - vehicle care
 - cooking
 - misc household tasks

Interfaces & Runtime Polymorphism!


In article about inheritance basics I mentioned that using interfaces offers great amount of flexibility when it comes to runtime polymorphism. Here are more details.

Although we can not instantiate an interface, but we can create an object of an interface and assign reference of any class implementing this interface.
If this statement sounds misleading, then have a look at following example:

Let's assume that we've an interface named IF1 as follows:
interface IF1{
void method1();
}

Further, there are two classes that implement this interface:
class C1 implements IF1{
void method1(){
// dummy code
}
void method2(int arg1){
// dummy code
}
}
class C2 implements IF1{
void method1(){
// dummy code
}
}

Have a look at following class that uses runtime polymorphism:
class1 Test1{
void method1(){
IF1 inf = null;
if (some condition){
inf = new C1(); // STMT1
} else {
inf = new C2(); // STMT2
}
}
}


As you can see in above example, STMT1 assigns referrence of an object of class C1 to inf, whereas STMT2 assigns referrence of an object of class C2 to inf. This provides great amount of flexibility at runtime.

Notice that the classes may implement any other methods as well; but the interface won't have any knowledge about them. In above example, inf will not be able to call method2.

NOTE: Runtime polymorphism is costly in terms of memory consumption, so use it cautiously for performance centric applications.