Method Overriding in Java
1.In java, whatever method parent class has that method by default available to the child class through inheritance. If the child class is not satisfied with parent class method implementation then child class is allowed to redefine that method based on its requirement, this process is known as "Overriding".
2.The parent class method which is overridden is called overridden method and the child class method which is overriding is called the overriding method.
3.In overriding method resolution is always takes care by JVM based on the runtime object hence overriding is also known as runtime polymorphism or dynamic polymorphism.
example:-
class Parent
{
public void m1( )
{
System.out.println("parent class method m1");
}
}
class Child extends Parent
{
public void m1( )
{
System.out.println("child class method m1");
}
}
class Test
{
public static void main(String [ ] args)
{
Parent p = new Parent( );
p.m1( );
Child c = new Child( );
c.m1( );
Parent p1 = new Child( );
p1.m1( );
}
}
output is :
Rules for Overriding
In overriding method sinature must be same means method name and argument types must be matched.
In Overriding return type must be same.
Parent class private methods not available to the child and hence overriding concept not applicable for private methods.
If based on our requirement we can define the exactly same private method in child class.This is valid but this is not overriding.
We can't override the parent class final method in the child class.If we are trying to override, we will get Compile-Time Error.
If child class method throws any checked exception compulsory parent class method should throw the same checked exception or its parent. Otherwise, we will get Compile -Time Error.There is no restriction for the unchecked exception.
No comments:
Post a Comment
Be the first to comment!
Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.
Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
Regards,
JavaByChetan
Back To Home