Super class in java || Using super class in java || What is the use of super class in java || Explain super class in java with example.|| Example of super class in java. || A Superclass Variable Can Reference a Subclass Object



Using super


Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super.

Using super to Call Superclass Constructors:

A subclass can call a constructor method defined by its superclass by use of the following form of super:

super(parameter-list);

Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor. We can overload super() as other methods and constructors are overloaded. When a subclass calls super( ), it is calling the constructor of its immediate superclass. Thus, super( ) always refers to the superclass immediately above the calling class. This is true even in a multileveled hierarchy. Also, super( ) must always be the first statement executed inside a subclass constructor.

Example




NOTE: In error situation ―Wheels‖ and ―Name‖ is private to class Vehicle so they can’t be accessed by any code outside the Vehicle class so for the solution there must be a public method to give access to its members it can be a constructor. So super is used in solution which calls the Vehicle class constructor to initialise its members.
A Second Use for super

super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used.
Syntax: 
super.memberOfsuperClass

member can be either a method or an instance variable.
For the example u can see instance variable hiding concept in this keyword example.

A Superclass Variable Can Reference a Subclass Object
A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. When a reference to a subclass object is assigned to a superclass reference variable, you will have access only to those parts of the object defined by the super class.
Example:

class Vehicle
{
int Wheels;
String color;
}
class Car extends Vehicle
{
String carName;
}
class VehicleTest
{
public static void main(String args[])
{
Vehicle myVehicle = new Vehicle(); //Reference of superclass
Car myCar = new Car(); //Reference of subclass
myCar.carName = "Honda"; //Sub class member
myCar.color = "Green"; //Super class member
myCar.Wheels = 4; //Super class member
myVehicle = myCar; //reference of subclass assigned to
// reference variable of super
myVehicle.color = "Red"; //Correct
myVehicle.carName = "Mistubishi"; //Generates an error
}
}

Post a Comment

Please do not enter any spam link in the comment box