What is meant by method overriding in Java?


Method overriding in Java


The meaning of method overriding is that You have parent class which has any method and you inherits that class so you can call that method at run time. but, If you want specific behavior when that method is called then you can override it. See below example.

       

 public class Animal {
 public Animal(String name) {
  super();
  this.name = name;
 }
 private String name;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public void display(){
  System.out.println("Displaying Animal. name = "+name);
 }  
 }

public class Dog extends Animal {
   public Dog(String name) {
      super(name);
   }
   public static void main(String[] args) {
      Animal dog = new Dog("Abc");
      dog.display();
   }
}


       
 
When you run the Dog class it will display below output.
       
o/p: Displaying Animal. name = Abc


 

Now when you edit the Dog class as below.

       

 public class Dog extends Animal {
     public Dog(String name) {
        super(name);
     }
     public static void main(String[] args) {
        Animal dog = new Dog("Abc");
        dog.display();
     }
    @Override
    public void display() {
        System.out.println("Displaying the Dog. name = "+getName());
    }
}


       
 

When you run the Dog class again it will display below output.

       


o/p: Displaying the Dog. name = Abc


 

Here yo can see you creates Dog object in both case. When you do not override the parent class method display() it will call parent class method. but when you override that method in child class Dog it will call own display() method at run time. 

Comments

Popular posts from this blog

How do I create an array of a string?

Explain briefly about POJO in Java?