What is super java

What is super java

Answer : In java super has two forms:

  • First used to calls the superclass constructor
  • Second used to access a member of the superclass that has been hidden by a member of a subclass.

Example 1 calling superclass constructor:

Note: subclass can call constructor defined in its superclass with use of the following form of super:

super(arg-list);

arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass constructor.

package com.javahonk.stringtest;

public class Department extends Employee {

    String departmentName;    

    public Department(String firstName, String lastName,
	    String departmentName) {
	super(firstName, lastName);
	this.departmentName = departmentName;
    }

    public static void main(String[] args) {

	Department department=
		new Department("Java", "Honk", "IT");
	System.out.println("First Name: "+department.firstName
		+" Last Name: "+department.lastName
		+" Deppartment: "+department.departmentName);	

    }
}

class Employee {

    String firstName;
    String lastName;

    public Employee(String firstName, String lastName) {
	super();
	this.firstName = firstName;
	this.lastName = lastName;
    }

}

 

Output:

What is super java

 

Example 2 when super used to access a member of the superclass that has been hidden :

package com.javahonk.stringtest;

public class Department extends Employee {

    // overrides printSubClassMethod in Superclass
    public void testMethod() {
	super.testMethod();
        System.out.println("I am in subclass.");
    }

    public static void main(String[] args) {

	Department department= new Department();
	department.testMethod();
    }
}

class Employee {

    public void testMethod() {
        System.out.println("I am in Superclass.");
    }

}

 

Output:

What is super java

 

Leave a Reply

Your email address will not be published. Required fields are marked *