2. Super keyword:
The super is a reference variable that is used to refer immediate parent
class objects.
Use:
1. Super() is used to refer the immediate parent class instance
variables.
2. Super() is used to invoke immediate parent class constructor.
3. Super() is used to invoke immediate parent class methods.
Example:
ClassVehicle
{
Int speed=100;
}
ClassBike extendsvehicle
{
Int speed=50;
Voiddisplay()
{
System.out.println(“speed=”+super.speed);
}
Publicstaticvoidmain(Stringarr[])
{
Bike b= new Bike();
b.display();
}
}
Output:speed=100
Example:the followingprogram show the use of superfor immediate parent class constructor
invocation
6. }
classC extendsB
{
publicC()
{
System.out.println("i amin c");
}
publicstaticvoidmain(Stringarr[])
{
A x= newA();
B y=newB();
C z=newC();
}
}
Output:
I am inA
I am inA
I am inA
I am inc
{
Super();
}
}
classC extendsB
{
publicC()
{
Super();
System.out.println("i amin c");
}
publicstaticvoidmain(Stringarr[])
{
A x= new A();
B y=new B();
C z=new C();
}
}
Explanation:
In javaeach classis a director indirectsubclassof java.lang.Object;
At the time of compilationcompileradds extendsObjectto definitionofeachindependent
class.
In case of inheritance eachsubclass inheritsdata memberfrom its superclassconstructor.
Compilerdo the following:
1. If a userdefinedclassdoesnothave aconstructor thencompileraddsadefault
constructorand writesSuperkeywordinit.
2. If a userdefinedclasshasconstructor thencompilerwritessuperkeywordtoeachof
the constructor whichdoesnotcontainsThisor superkeywordasitsfirststatement.
Difference between method overloading and method
overriding.
Overloading overriding
1. Method overloading is used Method overriding is used to
7. to increase the readability of
the program
provide the specific
implementation of the method
that is already provided by its
super class
2. Method overloading is
performed with in a class
Method overriding occurs in the
class that has IS-A relationship
3. In case of method
overloading parameter must
be different.
In case of method overriding
parameter must be same
Question: why we cannot override static method.
Ans: because static method is bound with class whereas
instance method is bound to object. Static belongs to class
area and instance belongs to heap area.