Super keyword in java
Super Keyword in Java:-
- The super keyword in java is a reference variable that is used to refer parent class objects.
- The keyword “super” came into the picture with the concept of Inheritance
Use of super keyword is as followed :-
- This scenario occurs when a derived class and base class has same data members.
- In that case there is a possibility of ambiguity for the JVM.
- We can understand it more clearly using this code snippet
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
2. Use of super with methods:
This is used when we want to call parent class method.
So whenever a parent and child class have same named methods then to resolve ambiguity we use super keyword.
This code snippet helps to understand the said usage of super keyword.
class Animal
{
void eat(){System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
3. Use of super with constructors:
super keyword can also be used to access the parent class constructor.
One more important thing is that, ‘’super’ can call both parametric as well as non parametric constructors depending upon the situation.
Following is the code snippet to explain the above concept:
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[])
{
Dog d=new Dog();
}
}
*********************************************************************************************************
Comments
Post a Comment