World's most popular travel blog for travel bloggers.

Super Keyword

, , No Comments
In the previous chapter of inheritance we have learnt about the different rules of method overriding, In this chapter we will be learning about the super keyword –

3 ways of Using Super Keyword :

Super is used to refer the immediate parent of the class. Whenever we create an object of the child class then the reference to the parent class will be created automatically.
We can user super keyword by using three ways –
  • Accessing Instance Variable of Parent Class
  • Accessing Parent Class Method
  • Accessing Parent Class Class Constructor

Way 1 : Accessing Instance Variable of Parent Class using Super

package com.c4learn.inheritance;

public class ParentClass {
    int ageClass = 100;
 
    public static void main(String[] args) {
        ChildClass c1 = new  ChildClass();
        c1.display();
        
    }
}

class ChildClass extends ParentClass{
    int ageClass = 200;

    public void display() {
 System.out.println("ageClass : " + ageClass); 
    }
}
Output of the Program
ageClass : 200
Consider the above example –
  1. We have same variable declared inside the parent class as well as in child class.
  2. Whenever we try to access the variable using the object of child class, always instance variable of child will be returned.
Suppose we want to access the the same variable from the parent class then we can modify the display() method as below –
public void display() {
     System.out.println("ageClass : " + super.ageClass);
}

Way 2 : Accessing Parent Class Method using Super

package com.c4learn.inheritance;

public class ParentClass {
    int ageClass = 100;
 
    public int getValue() {
     return 20;
    }
    
    public static void main(String[] args) {
        ChildClass c1 = new  ChildClass();
        c1.display();        
    }
}

class ChildClass extends ParentClass{
    int ageClass = 200;

    public int getValue() {
     return 50;
    }
    
    public void display() {
      System.out.println("result : " + super.getValue());
    }
}

Output :

result : 20
In this example we have same method declared inside parent and child class.
public void display() {
     System.out.println("result : " + super.getValue());
}
In order to execute the parent method from the child class we need to use super keyword.

Way 3 : Accessing Parent Class Constructor using Super

We will be learning super keyword and constructor in more details in the next chapter.

0 comments:

Post a Comment

Let us know your responses and feedback