In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
If subclass (child class) has the same method as
declared in the parent class, it is known as method overriding in Java.
Method overriding is used for runtime polymorphism. The
version of a method that is executed will be determined by the object that is
used to invoke it. If an object of a parent class is used to invoke the method,
then the version in the parent class will be executed, but if an object of the
subclass is used to invoke the method, then the version in the child class will
be executed.
Rules for Java Method Overriding
- The method must have the same name as in the parent class
- The method must have the same parameter as in the parent class.
- There must be an IS-A relationship (inheritance).
Example:
// Base Class
class Parent {
void
show()
{
System.out.println("Parent's
show()");
}
}
// Inherited class
class Child extends Parent {
void
show() //override method
{
System.out.println("Child's
show()");
}
}
class Main {
public
static void main(String[] args)
{
Parent
obj1 = new Parent();
obj1.show();
Parent obj2 = new Child();
obj2.show();
}
}
Points to note:
1.
Overriding and Access-Modifiers: The access
modifier for an overriding method can allow more, but not less, access
than the overridden method.
For example, a protected instance method in the
super-class can be made public, but not private, in the subclass.
2.
Final methods cannot be overridden
3.
Static methods cannot be overridden (When a
static method is defined with same signature as a static method in base class,
it is known as method hiding).
Difference between method overloading
and method overriding
Method
Overloading |
Method
Overriding |
|
1) |
Method overloading is used to increase the
readability of the program. |
Method overriding is used to provide the
specific implementation of the method that is already provided by
its super class. |
2) |
Method overloading is performed within class. |
Method overriding occurs in two classes that
have IS-A (inheritance) relationship. |
3) |
In case of method overloading, parameter
must be different. |
In case of method overriding, parameter
must be same. |
4) |
Method overloading is the example of compile
time polymorphism. |
Method overriding is the example of run
time polymorphism. |
No comments:
Post a Comment