Saturday, August 25, 2018

What Is Purpose Of Super Keyword Inwards Java?

| Saturday, August 25, 2018
Earlier nosotros stimulate got talked almost method overriding concept inwards coffee during THIS POST to modify the implementation of nurture class's method inwards sub class. In inheritance, Super keyword is used to refer object of immediate nurture class. Generally nosotros are using super keyword inwards inheritance for 3 unlike purpose. Let's run across how as well as when to usage super keyword inwards java. Interviewer tin enquire yous this query as well as then delight sympathise how it works.

super keyword usage
  1. To refer to the variable of nurture class.
  2. To invoke the constructor of immediate nurture class.
  3. To refer to the method of nurture class.
Let's stimulate got 1 illustration to sympathise higher upwards 3 things. We stimulate got nurture course of teaching Animal and it's sub class Elephant as bellow.

Animal.java
public course of teaching Animal {  int age = 40;  Animal(){   System.out.println("Animal is moving.");  }    void welcome(){   System.out.println("Welcome to Animal class.");  } }



Elephant.java
public course of teaching Elephant extends Animal {  int age = 100;   Elephant() {   // To invoke nurture course of teaching constructor Animal().   super();   System.out.println("Elephant is running.");    welcome();   // Used super.welcome() to telephone band nurture course of teaching method.   super.welcome();  }   void showAge() {   System.out.println("Average historic menstruum of Elephant : " + age);   // Used super.age to access nurture course of teaching variable value.   System.out.println("Average historic menstruum of Animals : " + super.age);  }   void welcome() {   System.out.println("Welcome to Elephant class.");  }   populace static void main(String[] args) {   Elephant c = novel Elephant();   c.showAge();  } }

Output
Animal is moving. Elephant is running. Welcome to Elephant class. Welcome to Animal class. Average historic menstruum of Elephant : 100 Average historic menstruum of Animals : 40

In higher upwards illustration yous tin run across that nosotros stimulate got used
  1. super.age to refer nurture course of teaching variable age.
  2. super() to invoke immediate nurture course of teaching constructor Animal() and
  3. super.welcome() to access nurture course of teaching method.
This means yous tin invoke constructor of nurture course of teaching inwards to tyke course of teaching or access nurture course of teaching variable or method when same advert method or variable is available inwards tyke class.

<< PREVIOUS || NEXT >>

Related Posts