super keyword is a reference variable in Java.
super Keyword:
class Parent
{
int num = 100;
}
class Child extends Parent
{
int num = 200;
void display()
{
System.out.println("Child num: " + num);
System.out.println("Parent num: " + super.num); // referring to parent class variable
}
}
public class SuperDemo
{
public static void main(String[] args)
{
Child c = new Child();
c.display();
}
}
Child num: 200 Parent num: 100
class Parent
{
void showMessage()
{
System.out.println("Hello from Parent class showMessage() method");
}
}
class Child extends Parent
{
void display()
{
// Calling parent class method using 'super'
super.showMessage();
System.out.println("Inside Child class display() method");
}
}
public class SuperDemo
{
public static void main(String[] args)
{
Child obj = new Child();
obj.display();
}
}
Hello from Parent class showMessage() method Inside Child class display() method
package notesprogram;
class Parent
{
Parent()
{
System.out.println("Parent constructor called");
}
}
class Child extends Parent
{
Child()
{
super(); // calls Parent's constructor
System.out.println("Child constructor called");
}
}
public class SuperDemo
{
public static void main(String[] args)
{
Child c = new Child();
}
}
Parent constructor called Child constructor called
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.