Super Keyword in Java



The super keyword refers to the superclass (parent) class object

super keyword can be used to refer to the parent class instance variable.
super keyword can be used to invoke the parent class method.
super keyword can be used to invoke parent class constructor.

For Practice:


public class SuperKeyExample {

 public static void main(String[] args) {

  NewClass ncObj = new NewClass();

  ncObj.show();
 }

}



class SuperClass { 

 int a = 10; 

 SuperClass()
 {
  System.out.println("Super/Base class constructor");
 }

 

 void show()
 {
  System.out.println("Base class member method");
 }
 

}



class NewClass extends SuperClass {
 int a = 20;
 

 NewClass()
 {
  super();//implitly super keyword used here

  System.out.println("New Class constructor");
 }
 

 void show()
 {
  super.show(); //invoke the base class method using super keyword
  System.out.println(a);
  System.out.println(super.a); //Access the base class variable using super keyword
 }

}

Comments

Popular posts from this blog

Google Assistant Implementation in Android application with app actions