8/11/07

Reference vs. Instance variables in java

Java is a mature language, so posting an article about it would not make sense. However,

Imagine you have following two classes:

public class TheParent{ public doParentThing(){} } public class TheChild extends TheParent{ public doChildThing(){}
public doParentThing(){} //overrride
}


Ok, now lets instantiate TheChild :

TheChild obj=new TheChild;

it's ok to invoke two methods:
obj.doParentThing(); //TheChild version invokes
obj.doChildThing();

now, instantiate it polymorphically:

TheParent obj=new TheChild();

if we try to invoke doChildThing() we get a compile error and when we invoke:

obj.doParentThing();

the TheChild's doParentThing() override invokes.

This is true when we get a reference to an interface that the instance variable's class implement. in such a case, we can ONLY invoke the methods blueprinted by the interface.

0 comments: