SUPER KEYWORD IN JAVA

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.

Usage of Java super Keyword

  1. super can be used to refer immediate parent class instance variable.
  2. super can be used to invoke immediate parent class method.
  3. super() can be used to invoke immediate parent class constructor.

super can be used to invoke parent class method


class Animal

{

void eat()

{

System.out.println(“eating…”);

} }

class Dog extends Animal

{

void eat()

{

System.out.println(“eating bread…”);

}

void bark()

{

System.out.println(“barking…”);

}

void work()

{

super.eat();

bark();

} }

class TestSuper2

{

public static void main(String args[])

{

Dog d=new Dog(); d.work();

}
}
Output:
eating… barking…

super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor.


Let’s see a simple example:


class Animal

{

Animal()

{

System.out.println(“animal is created”);

} }

class Dog extends Animal

{

Dog()

{

super();

System.out.println(“dog is created”);

}}

class TestSuper3

{

public static void main(String args[])

{

Dog d=new Dog();

}
}
Output:
animal is created dog is created

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *