12 Java Polymorphism- super keyword
12 Java Polymorphism- super keyword
The ‘super’ keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class.
1. class Animal{
2. String color="white";
3. }
4.
5. class Dog extends Animal{
6. String color="black";
7.
8. void printColor(){
11. }
12.
13. }
18. }}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.
The super keyword can also be used to invoke parent class method. It should be used
particularly if subclass contains the same method as parent class. In other words, it is used if
method is overridden.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4.
5. class Dog extends Animal{
6.
7. void eat(){System.out.println("eating bread...");}
8.
9. void bark(){System.out.println("barking...");}
10.
11. void work(){
12. super.eat();
13. bark();
14. }
15. }
16. class TestSuper2{
17. public static void main(String args[]){
18. Dog d=new Dog();
19. d.work();
20. }}
Output:
Eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given
to local.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
1. class Animal{
2. Animal()
3. {
4. System.out.println("animal is created");
5. }
6. }
7.
8. class Dog extends Animal{
9. Dog(){
10. super();
11. System.out.println("dog is created");
12. }
13. }
14. class TestSuper3{
17. }}
Output:
animal is created
dog is created
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}
Output:
animal is created
dog is created
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class
constructor.
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
13. this.salary=salary;
14. }
21. }}
Output:
1 ankit 45000