Method Overriding

In Inheritance, we saw that how a parent class properties or functions we can derive in the child or derived class. Now to understand the concept of Method Overriding child class must derive the property of the parent class and the condition is we need to keep the Name of the Method and Parameter should be same as parent class method.

Note: Without  Inheritance Method Overriding is not possible.

  • Method Overriding is used to provide a specific implementation of a method that is already provided by its superclass.
  • Method Overriding is used for Runtime Polymorphism

Example:

class Parent
{ 
     String surName = " Diwan ";
     void display(){
     System.out.println("Parents Surname" + surName);
     } 
} 
class child extends Parent
{ 
     void display(){
     super.display(); // super is used to call parent class method.
     System.out.println("Child Surname" + surName);
     } 
} 

class MethodOverriding
{ 
     public static void main(String args[]){ 
     Dog child = new child(); 
     c.display();  
     }
}

Output:

Parent surname Diwan
Chilsd surname Diwan

Super Keyword

Here, super keyword is used to call the parent class method or variables in a child class.

Syntax:      super.methodName(); or super.variableName;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: