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

Similar Programs Chapter Last Updated
Java Final Class Inheritance 02-08-2017
Java Final Method In Inheritance Inheritance 02-08-2017
Java Multilevel Hierarchical Inheritance Inheritance 01-08-2017
Java Super To Invoke Parent Class Method Inheritance 31-07-2017
Java Super To Invoke Parent Class Constructor Inheritance 30-07-2017
Static And Dynamic Binding In Java Inheritance 24-03-2017
Java Overloaded Method To Print Array Inheritance 03-09-2016
Dynamic Method Dispatch In Java Example Inheritance 19-06-2016
Abstract Class In Java Example Inheritance 20-07-2016
Method Overloading In Java Example Inheritance 20-07-2016
Inheritance And Constructors In Java Inheritance 20-07-2016
Multilevel Inheritance In Java Example Inheritance 22-09-2018
Super() In Java Example Inheritance 14-07-2016
Inheritance In Java Example Inheritance 20-07-2016

1