// A simple program to demonstrate method overriding in Java
// Driver class
class Overriding {
public static void main( String[ ] args ) {
// If a Parent type reference refers to a Parent object,
// then the Parent's show() is called.
Parent obj1 = new Parent( args[0] );
obj1.show( );
// If a Parent type reference refers to a Child object,
// then the Child's show() is called.
// This is called RUN TIME POLYMORPHISM.
Parent obj2 = new Child( args[0], args[1] );
obj2.show( );
}
}
// Base class
class Parent {
String name;
Parent( String name ) { this.name = name; }
void show( ) {
System.out.println( "Show( ) of Parent (" + this.name + ")" );
}
}
// Inherited class
class Child extends Parent {
String name;
Child( String pName, String cName ) {
super( pName );
this.name = cName;
}
// This method overrides Parent's show().
@Override
void show( ) {
System.out.println( "Show( ) of " + super.name + "'s Child (" + this.name + ")" );
}
}
|