We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8
Super Keyword
• 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 1. super is used to refer immediate parent class instance variable: • We can use super keyword to access the data member or field of parent class. • It is used if parent class and child class have same fields. Eg: class A { int x= 10; } class B extends A { int x = 20; void display() { System.out.println(x);//prints x of B class System.out.println(super.x);//prints x of A class } } class TestSuper1 { public static void main(String args[]) { B d=new B(); d.display(); 2. super can be used to invoke parent class method: • The super keyword can also be used to invoke parent class method. • It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden Eg: class A { void eat(){System.out.println("eating...");} } class B extends A { void eat(){System.out.println("eating bread...");} void work() { super.eat(); eat(); } } class TestSuper2{ public static void main(String args[]){ Dog d=new Dog(); d.work(); }} 3. super is used to invoke parent class constructor. • The super keyword can also be used to invoke the parent class constructor Eg: 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(); }}