Overriding in Java Programming

Overriding in Java Programming

Previous Home Next

 

If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final.

The benefit of overriding is:- ability to define a behavior that's specific to the sub class type.
 Which means a subclass can implement a parent class method based on its requirement.
 In object oriented terms, overriding means to override the functionality of any existing method.

Rules for overriding
1.The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
2.Instance methods can be overridden only if they are inherited by the subclass.
3.A method declared final cannot be overridden.
4.If a method cannot be inherited then it cannot be overridden.

Super key word

When invoking a superclass version of an overridden method the super keyword is used.
 


 
class Animal
{

public void move()
{
System.out.println("Animals can move");
}
}

class Cat extends Animal
{

public void move()
{
System.out.println("Cat can walk and run");
}
}

public class Cat1
{

public static void main(String args[])
{
Animal a = new Animal(); // Animal reference and object
Animal b = new cat(); // Animal reference but Cat object

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

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


Method overriding using Super keyword

class Animal
{

public void move()
{
System.out.println("Animals can move");
}
}

class Cat extends Animal
{

public void move()
{
super.move(); // invokes the super class method
System.out.println("Cats can walk and run");
}

}

public class Cat1
{

public static void main(String args[]){

Animal b = new Cat(); // Animal reference but Cat object
b.move();//Runs the method in Cat class

}
}







Previous Home Next