Thursday, June 01, 2006

Virtual Method Invocation

Although methods can take advantage of virtual method invocation, variables cannot. Variables are always bound to the reference type. This is important to understand if you provide the same variable name in both a superclass and a subclass.

public class SuperVariableDemo
{
public String str = “Superclass”;
}
public class SubVariableDemo extends SuperVariableDemo
{
public String str = “Subclass”;
public static void main(String[] args)
{
SuperVariableDemo sd = new SubVariableDemo();
System.out.println(sd.str);
}
}

The output will always be Superclass even though the runtime type is SubVariableDemo. Remember that instance methods are always bound to the runtime type, and instance variables are always bound to the reference type. If you commit this to memory right now, you will avoid some strange and pesky bugs in the future!

The reference type rule for methods:

The rule is that if you try to call a method via an object reference, that method must be defined in the class of the reference type to begin with. You simply cannot directly call a method solely defined in a subclass if you reference that object with the superclass type.

3 Comments:

At 11:26 PM, Blogger Mahender Kandyanam said...

This comment has been removed by the author.

 
At 11:27 PM, Blogger Mahender Kandyanam said...

I tried out above example. I could see subclass value not super class... whats that mean.?

 
At 11:27 PM, Blogger Mahender Kandyanam said...

This comment has been removed by the author.

 

Post a Comment

<< Home