Search for more details......

Overriding Methods in Java



Override methods in java when you want to customize methods on a parent class

So to override methods, You must have a supper class and a child class.
 
And write method  that is to be overridden  in the child class as same as in the Parent(super) class.

Overridden method mus be wider access level than the supper class. (default and public are the allowed access levels to a overridden method.



Example:

public class Animal{//This is the parent class to represent an animal

      public int getLegsCount(){

      }

}

public class Human extends Animal{ //Human is an animal, and human has 2 legs
      private final int legs=2;
      public int getLegsCount(){ //This method is overridden by Animal class

                 return legs;
      }

}

public class Dog extends Animal{ //Dog is an animal, dog has 4 legs
      private final int legs=4;
      public int getLegsCount(){//This method is overridden by Animal class

               return legs;
      }
}



No comments:

Post a Comment