Method Overriding In Java Example
Chapter:
Inheritance
Last Updated:
20-07-2016 03:25:28 UTC
Program:
/* ............... START ............... */
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class JavaMethodOverriding {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();// Runs the method in Dog class
}
}
/* ............... END ............... */
Output
Animals can move
Dogs can walk and run
Notes:
-
If subclass (child class) has the same method as declared in the parent class,
- it is known as method overriding in java.
- Method overriding is used to provide specific implementation of a method that is already provided by its super class.
- Method overriding is used for runtime polymorphism.
- The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class(base class).
Tags
Method Overriding, Java