Usage of super keyword
1. super() invokes the constructor of the parent class.
2. super.variable_name refers to the variable in the parent class.
3. super.method_name refers to the method of the parent class.
1. super() invokes the constructor of the parent class.
super() will invoke the constructor of the parent class. Even when you don’t add
super() keyword the compiler will add one and will invoke the Parent Class
constructor. You can also call the parameterized constructor of the Parent Class
class ParentClass
{
public ParentClass()
{
[Link]("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
public SubClass()
{
//super();
[Link]("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output: Parent Class default Constructor
Child Class default Constructor
2. super.variable_name refers to the variable in the parent class
class ParentClass
{
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;
public void disp()
{
[Link]("Value is : "+[Link]);
}
public static void main(String args[])
{
SubClass s = new SubClass();
[Link]();
}
}
Value is : 999
3. super.method_nae refers to the method of the parent class
class ParentClass
{
public void disp()
{
[Link]("Parent Class method");
}
}
public class SubClass extends ParentClass
{
public void disp()
{
[Link]("Child Class method");
}
public void show()
{
//Calling SubClass disp() method
disp();
//Calling ParentClass disp() method
[Link]();
}
public static void main(String args[])
{
SubClass s = new SubClass();
[Link]();
}
}
Child Class method
Parent Class method