Saturday, March 4, 2017

Super() in Java

Tags

Keyword Super is used to refer to the immediate Superclass in case of Inheritance from the Subclass.It is used to call the constructor in case of constructor overloading because without this default constructor is called.

It is used in two forms:

1.Super is used to call the constructor of the Superclass in Subclass Constructor.

Syntax:: super(parameter  list)

Code::

import java.util.*;
class Base
{
    Scanner in=new Scanner(System.in);
    int a,b;
    Base()
    {
        System.out.print("Enter Value of a:");
        a=in.nextInt();
        System.out.print("Enter Value of b:");
        b=in.nextInt();
       
    }
    void show()
    {
        System.out.println(a+b);
    }
}
class Derived extends Base
{
    Scanner in=new Scanner(System.in);
    int c;
    Derived()
    {
        super();
        System.out.print("Enter Value of c:");
        c=in.nextInt();
    }
    void display()
    {
        System.out.println(a+b+c);     // a,b are the members of superclass
    }
}
public class Inheritance
{

    public static void main(String[] nt)
    {
        Derived ob2=new Derived();
        System.out.print("Sum is:");
        ob2.display();
    }
}

Output::