Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Super in Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

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()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
public SubClass()
{
//super();
System.out.println("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()


{
System.out.println("Value is : "+super.val);
}

public static void main(String args[])


{
SubClass s = new SubClass();
s.disp();
}
}
Value is : 999

3. super.method_nae refers to the method of the parent class


class ParentClass
{
public void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{

public void disp()


{
System.out.println("Child Class method");
}

public void show()


{
//Calling SubClass disp() method
disp();
//Calling ParentClass disp() method
super.disp();
}
public static void main(String args[])
{
SubClass s = new SubClass();
s.show();
}
}
Child Class method
Parent Class method

You might also like