Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

What is method overriding?

user-image
Question ajoutée par mayank semwal
Date de publication: 2013/11/17

when the subclass can modify the methods inherited from its parent class that's called overriding, thus an instance method with the same signature &return type as a method in the super class is said to override it

Utilisateur supprimé
par Utilisateur supprimé

Method overriding is the ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it override source: Oracle Java

An Example: 

classAnimal{

 

   publicvoid move(){

      System.out.println("Animals can move");

   }

}

 

classDogextendsAnimal{

 

   publicvoid move(){

      System.out.println("Dogs can walk and run");

   }

}

 

publicclassTestDog{

 

   publicstaticvoid main(String args[]){

      Animal a =newAnimal();// Animal reference and object

      Animal b =newDog();// Animal reference but Dog object

 

      a.move();// runs the method in Animal class

 

      b.move();//Runs the method in Dog class

   }

}Results :

Animals can move

Dogs can walk and run

 

 

I hope I have well answered your question, if it’s not let me know and I’ll give you more explanations 

More Questions Like This