Before reading this post i would suggest you to read about Relationship in JAVA .In case of inheritance,subclass will inherit the features of superclass.If any method is defined in superclass and if subclass also want to implement the same method but want to change the functionality, then the same method is declared in subclass with different functionality. Let us consider the example of animal class and gangaroo class as subclass.
public class Animal {
public void run(){
System.out.println("Animals run with four legs");
}
public static void main(String[] args) {
System.out.println("How animal runs?");
Animal animal=new Animal();
animal.run();
System.out.println("How Gangaroo runs");
Gangaroo garoo=new Gangaroo();
garoo.run();
}
}
class Gangaroo extends Animal{
public void run(){
System.out.println("Gangaroo run with two legs");
}
}
output:
How animal runs?
Animals run with four legs
How Gangaroo runs
Gangaroo run with two legs
In the above example,gangaroo class also needs to implement the same run() method of Animal class but wanted to change the functionality.Hence gangaroo class also implements the run method with different functionality. This concept of implementing the same method as that of super class
with change in functionality in subclass is called method overridding.
A method is said to be overrided when method name,parameters passed and return type of the method should be same as that of the method defined in parent class.
Following methods cannot be overrided
i] static methods
ii] private methods
public class Animal {
public void run(){
System.out.println("Animals run with four legs");
}
public static void main(String[] args) {
System.out.println("How animal runs?");
Animal animal=new Animal();
animal.run();
System.out.println("How Gangaroo runs");
Gangaroo garoo=new Gangaroo();
garoo.run();
}
}
class Gangaroo extends Animal{
public void run(){
System.out.println("Gangaroo run with two legs");
}
}
output:
How animal runs?
Animals run with four legs
How Gangaroo runs
Gangaroo run with two legs
In the above example,gangaroo class also needs to implement the same run() method of Animal class but wanted to change the functionality.Hence gangaroo class also implements the run method with different functionality. This concept of implementing the same method as that of super class
with change in functionality in subclass is called method overridding.
A method is said to be overrided when method name,parameters passed and return type of the method should be same as that of the method defined in parent class.
Following methods cannot be overrided
i] static methods
ii] private methods
Sign up here with your email
ConversionConversion EmoticonEmoticon