• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Super Keyword

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

MSK TechnologiesTrainings

super. Program

class Parent
{
    int x=90; //parant class variable
}
class Child extends Parent
{
    int  x=30; //global variable
    void show()
    {
        int x=10;  //local variable
        System.out.println(x);  //ocal variable
        System.out.println(this.x); //global variable
        System.out.println(super.x); //parant class variable
    }
}
public 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)
    {
        Statement 1;
        Statement 2;
        ..
        ..
    }
}
class Child extends Parent
{
    Child(int x)
    {
        super(20); -->First statement of the constructor.
        Statement 3;
        Statement 4;
        ..
        ..
    }
}
super() -NoParameterized
class A
{
    A()
    {
        System.out.println("Parent constructor");
    }
}

class B extends A
{
    B()
    {
    
        System.out.println("child constructor");
    }
}

public class Main
{
    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");
    }
}

public class Main
{
    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");
    }
}

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

Output:
Parent constructor
Child constructor