• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Super Keyword


Super is a keyword in java language which is used in two different ways.
1.super.(dot)
2.super()

super. :
super.(dot) is used to differentiate parent class variables and child class variables whenever both are same name.
Syntax:
super.variablename;


Note:
super. always represents parent variables

super. Program

class Parent
{
int x=90;
}
class Child extends Parent
{
int x=30;
void show()
{
int x=10;
System.out.println(x);\\ local variable
System.out.println(this.x); \\ global variable
System.out.println(super.x); \\ parant class variable
}
}
class Main
{
public static void main(String args[])
{
Child c=new Child();
c.show();
}
}


Output:
Super()

super() is used to call the parent class constructor within derived class constructor.
Syntax:
super(arguments);
Note:
super() always first statement of the constructor.

class Parent
{
Parent(int x)
{
..
..
}
}
class Child extends Parent
{
Child(int x)
{
super(20); -->First statement of the constructor.
..
..
}
}

super() -NoParameterized
class A
{
A()
{
System.out.println("Parent constructor");
}
}
class B extends A
{
B()
{

System.out.println("child constructor");
}
}
class M
{
public static void main(String args[])
{
B ob =new B();
}
}


Output:
Parent constructor
child constructor
Note:
Default constructor called by the Parent class constructor with in derived constructor by default
super() -Parameterized

class A
{
A(int x)
{
System.out.println("Parent constructor");
}
}
class B extends A
{
B(int x)
{

System.out.println("child constructor");
}
}
class M
{
public static void main(String args[])
{
B ob =new B(10);
}
}


Output:
Error
Note:
Constructors can not inherit to one class to another class.
To overcome this problem super() is introduced;
super() -Parameterized

class A
{
A(int x)
{
System.out.println("Parent constructor");
}
}
class B extends A
{
B(int x)
{
super(20);
System.out.println("child constructor");
}
}
class M
{
public static void main(String args[])
{
B ob =new B(10);
}
}


Output:
Parent constructor
child constructor