freetimestudys@gmail.com          +91-7097633380
  Login Here                        

super keyword

super is a keyword that refers to the object of super class. Generally, we write sub class variables, constructors and methods in a class. Whenever data members of a class and formal parameters of a method or constructor is existing with same name then system will get confused to overcome this problem “super.” can be useful.

super class variables

class Test1
 {
int a=10;
int b=20;
};
class Test extends Test1
{
int a=100;
int b=200;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
System.out.println(super.a+super.b); 
 }
public static void main(String[] args)
 {
Test t=new Test();
t.add(1000,2000);
 }
};

intput and output

output:300,,3000,,30

super class methods

class Parent
 {
void m1()
  {
System.out.println("parent class method");
 }
};
class Child extends Parent
{
void m1()
  {
System.out.println("hi");
  }
void m2()
  {
this.m1();
System.out.println("hello");
super.m1();
 }
public static void main(String[] arhs)
{
Child c=new Child();
c.m2();
}
};

intput and output

output:hi,,hello,,parent class method

super class constructors

class Test1
 {
Test1(int i,int j)
 {
System.out.println(i+j);
}
};
class Test extends Test1
 {
Test(int i)
{
super(100,200);
System.out.println(i);
}
public static void main(String[] args)
{
Test t=new Test(10);
}
}

intput and output

output:300,,10

Note :-

   inside the constructors it is possible to call only one constructor at a time that calling must be first statement of the constructor.