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
public class ThisDemo
{
void showMessage()
{
System.out.println("Hello from showMessage() method");
}
void display()
{
// Calling another method of the same class using 'this'
this.showMessage(); // Optional: can also call showMessage() directly
System.out.println("Inside display() method");
}
public static void main(String[] args)
{
ThisDemo obj = new ThisDemo();
obj.display();
}
}
Hello from showMessage() method Inside 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.