Usage of Java Super Keyword
Usage of Java 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(object), an instance of parent class is created
implicitly which is referred by super reference variable.
1. class Animal
2. {
3. String color="white";
4. }
5. class Dog extends Animal
6. {
7. String color="black";
8. void printColor()
9. {
10. System.out.println(color);//prints color of Dog class
11. System.out.println(super.color);//prints color of Animal class
12. }
13. }
14. class TestSuper1
15. {
16. public static void main(String args[])
17. {
18. Dog d=new Dog();
19. d.printColor();
20. }
21. }
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.
EXAMPLE 2
void display()
{
/* print maxSpeed of subclass class (Car) */
System.out.println("Maximum Speed: " + maxSpeed);
Output:
Maximum Speed: 180
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We could acces
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void eat()
11. {
12. System.out.println("eating bread...");
13. }
14. void bark()
15. {
16. System.out.println("barking...");
17. }
18. void work()
19. {
20. super.eat();
21. bark();
22. }
23. }
24.
25. class TestSuper2
26. {
27. public static void main(String args[])
28. {
29. Dog d=new Dog();
30. d.work();
31. }
32. }
33. 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. {
3. Animal()
4. {
5. System.out.println("animal is created");
6. }
7. }
8. class Dog extends Animal
9. {
10. Dog()
11. {
12. super();
13. System.out.println("dog is created");
14. }
15. }
16. class TestSuper3
17. {
18. public static void main(String args[])
19. {
20. Dog d=new Dog();
21. }}
Output:
animal is created
dog is created