Java Online Compiler
Super
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;
                                            
    super . always represents parent class variable.
  • super():
  • super() is used to call the parent class constructor within derived class constructor.
                                                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.
Super

class Parent
{
int x=90;
}
class Child extends Parent
{
void show()
{
int x=10;
x=x; // super.x=x;  or x=super.x;

System.out.println(x);
}
}
class M
{
public static void main(String args[])
{
Child c=new Child();
c.show();
}
}

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(10);
System.out.println("child constructor");
}
}

class M
{
public static void main(String args[])
{
B ob =new B(10);
}
}


output:
Parent constructor
child constructor