Skip to content

Instantly share code, notes, and snippets.

@kenorb
Last active August 29, 2015 14:04
Show Gist options
  • Save kenorb/7f4900b631a5978b5e78 to your computer and use it in GitHub Desktop.
Save kenorb/7f4900b631a5978b5e78 to your computer and use it in GitHub Desktop.
Overridden Method Demo in Java.
/*
* OverriddenMethod Demo.
*
* Method overriding. In a class hierarchy when superclass and subclass have a method with the same name and same signature than the method in subclass then is set to be overriden method.
* It is the way of representing polymorphism.
* A superclass reference can refer to its subclass object, but a subclass reference cannot refer to superclass object.
*/
class A {
void display() {
System.out.println("From class A");
}
}
class B extends A { // Subclass of class A.
void display() { // Overridden method.
System.out.println("From class B");
}
}
class C {
void display() { // Normal method.
System.out.println("From class C");
}
}
class OverriddenMethod {
public static void main(String args[]) {
A a1 = new A();
B b1 = new B();
C c1 = new C();
a1.display();
b1.display();
c1.display();
A ref = b1; // Refers to the object of class B.
ref.display(); // Invokes display from class B.
ref = a1; // Refers to the object of class A.
ref.display(); // Invokes display from class A.
// ref = c1; // Error.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment