What Is Use Of Super Keyword In Java?

Earlier nosotros attain got talked close method overriding concept inwards coffee during THIS POST to modify the implementation of rear class's method inwards sub class. In inheritance, Super keyword is used to refer object of immediate rear class. Generally nosotros are using super keyword inwards inheritance for 3 dissimilar purpose. Let's run into how together with when to occupation super keyword inwards java. Interviewer tin inquire y'all this query together with then delight empathise how it works.

super keyword usage
  1. To refer to the variable of rear class.
  2. To invoke the constructor of immediate rear class.
  3. To refer to the method of rear class.
Let's accept ane illustration to empathise inwards a higher house 3 things. We attain got rear shape Animal and it's sub class Elephant as bellow.

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



Elephant.java
public shape Elephant extends Animal {  int age = 100;   Elephant() {   // To invoke rear shape constructor Animal().   super();   System.out.println("Elephant is running.");    welcome();   // Used super.welcome() to telephone telephone rear shape method.   super.welcome();  }   void showAge() {   System.out.println("Average historic current of Elephant : " + age);   // Used super.age to access rear shape variable value.   System.out.println("Average historic current 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 current of Elephant : 100 Average historic current of Animals : 40

In inwards a higher house illustration y'all tin run into that nosotros attain got used
  1. super.age to refer rear shape variable age.
  2. super() to invoke immediate rear shape constructor Animal() and
  3. super.welcome() to access rear shape method.
This agency y'all tin invoke constructor of rear shape inwards to pocket-sized fry shape or access rear shape variable or method when same advert method or variable is available inwards pocket-sized fry class.

<< PREVIOUS || NEXT >>

More interesting articles here :Generation Enggelmundus Internet Marketing Tool here :Zeageat IM http://www.software-testing-tutorials-automation.com/
Post a Comment (0)
Previous Post Next Post