Java- Method Overriding / Chapter - 7 / OOP's Concept

Method OverridingMethod 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 :Method Overriding

Rules for Overriding




  1. In overriding method sinature must be same means method name and argument types must be matched.



  2. In Overriding return type must be same.



  3. Parent class private methods not available to the child and hence overriding concept not applicable for private methods.



  4. If based on our requirement we can define the exactly same private method in child class.This is valid but this is not overriding.



  5. 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.



  6. 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

Flipkart End Of Season Sale






© Copyright 2017 Javabychetan.blogspot.com