What is overriding in Java can explain briefly with an example?

Java 8Object Oriented ProgrammingProgramming

If superclass and subclass have methods with same name including parameters. JVM calls the respective method based on the object used to call the method. i.e. if the current object using which the method is called, is of superclass type the method of the superclass is executed.

Or, if the object is of the type subclass then the method of the sub class is executed.

Example

 Live Demo

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 TestDog {
   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
   }
}

Output

Animals can move
Dogs can walk and run
raja
Published on 05-Jul-2019 12:37:44
Advertisements