Monday, March 23, 2015

Method overriding

Declaring a method in subclass which is already present in parent class is known as method overriding.

Examples:
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");
      }
}
 
class MethodOverridingDemo
{
      public static void main(String args[])
      {
              Animal aObj1 = new Animal(); 
              Dog dObj = new Dog();
              Animal aObj2 = new Dog(); 
             
              aObj1.move();
              dObj.move();
              aObj2.move();         // Dynamic method dispatch
       }
}
 


Output
Animals can move
Dogs can walk and run
Dogs can walk and run

No comments:

Post a Comment