Wednesday, December 12, 2018

Java OOPS: Inheritance (Overriding) Part 7 With Super keyword

Hi ,

In previous post , we checked that how method hiding takes place. Now in this post I am going to share some usage of super keyword.
In common language we can say that super keyword is used to invoke , parent class variable , method or constructor by child class members.

Let's take a look on some examples for better understanding:

Example :1  

Usage of super keyword , for variable invocation of Parent class. 

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
String color = "red";
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
String color = "green";
public void m1(){
System.out.println("Color Value in Child Class:"+color);
System.out.println("Color Value in Parent Class:"+super.color);
}
}

Output :

Color Value in Child Class:green
Color Value in Parent Class:red

Explanation:  

In this example we can see that I have used super.color to get the color value from Parent class.


Example :2  

Usage of super keyword , for method invocation of Parent class. 

public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m1(){
System.out.println("This is child class m1 method");
super.m1();
}
}

Output :

This is child class m1 method
This is parent class m1 method

Explanation:  

In this example we can see that I have used super.m1(); to call the m1() of Parent class.


Example :3

Usage of super keyword , for calling the parent class constructor 

public class InheritanceDemo1 {
public static void main(String [] args){
new Child();
}
}
class Parent {
public Parent() {
System.out.println("I am in parent class constructor");
}
}
class Child extends Parent {
public Child() {
super();
System.out.println("I am in child class constructor");
}
}

Output :

I am in parent class constructor
I am in child class constructor

Explanation:  

In this example we can see that I have used super(); to call the constructor of Parent class.



No comments:

Post a Comment