Polymorphism (Cont.)


Runtime Polymorphism with Data Members
We can override methods only, not the variables (data members), so runtime polymorphism cannot be achieved by data members:

DataMember.java (runtime polymorphism with data members)
// Runtime polymorphism cannot be achieved by data members.
public class DataMember {
  public static void main( String args[ ] ) {
    A a = new B( );     // Object of type B
    System.out.print( a.x );
  }
}
// class A 
class A { int x = 10; } 
// class B 
class B extends A { int x = 20; }
shell> java DataMember

Output:           Result:

In above program, both the class A (superclass) and B (subclass) have a common variable x. Now we make object of class B, referred by a which is of type of class A. Since variables are not overridden, so the statement a.x will always refer to data member of superclass.

Static vs Dynamic Binding



      “Perhaps the rare and simple pleasure of being seen for    
      what one is compensates for the misery of being it.”    
      ― Margaret Drabble