0% found this document useful (0 votes)
5 views17 pages

JAVA Super Keyword

The super keyword in Java is used to refer to the immediate parent class and allows subclasses to access parent class methods, variables, and constructors. It enables code reuse, supports polymorphism, and facilitates the customization of behavior in object-oriented programming. Key characteristics include its necessity as the first statement in a constructor, its inability to be used in static contexts, and its automatic invocation by the compiler if not explicitly called.

Uploaded by

gopogo56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views17 pages

JAVA Super Keyword

The super keyword in Java is used to refer to the immediate parent class and allows subclasses to access parent class methods, variables, and constructors. It enables code reuse, supports polymorphism, and facilitates the customization of behavior in object-oriented programming. Key characteristics include its necessity as the first statement in a constructor, its inability to be used in static contexts, and its automatic invocation by the compiler if not explicitly called.

Uploaded by

gopogo56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever we create the instance of subclass, an instance of parent class is created


implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

Characteristics of Super Keyword in Java


In Java, super keyword is used to refer to the parent class of a subclass.
Here are some of its key characteristics:
 super is used to call a superclass constructor: When a subclass is
created, its constructor must call the constructor of its parent class.
This is done using the super() keyword, which calls the constructor of
the parent class.
 super is used to call a superclass method: A subclass can call a
method defined in its parent class using the super keyword. This is
useful when the subclass wants to invoke the parent class’s
implementation of the method in addition to its own.
 super is used to access a superclass field: A subclass can access a
field defined in its parent class using the super keyword. This is useful
when the subclass wants to reference the parent class’s version of a
field.
 super must be the first statement in a constructor: When calling a
superclass constructor, the super() statement must be the first
statement in the constructor of the subclass.
 super cannot be used in a static context: The super keyword cannot
be used in a static context, such as in a static method or a static
variable initializer.
 super is not required to call a superclass method: While it is
possible to use the super keyword to call a method in the parent class,
it is not required. If a method is not overridden in the subclass, then
calling it without the super keyword will invoke the parent class’s
implementation.
Overall, the super keyword is a powerful tool for subclassing in Java,
allowing subclasses to inherit and build upon the functionality of their
parent classes.
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used
if parent class and child class have same fields.

EXAMPLE 1

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
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

// super keyword in java example

// Base class vehicle

class Vehicle {

int maxSpeed = 120;

}
// sub class Car extending vehicle

class Car extends Vehicle {

int maxSpeed = 180;

void display()

// print maxSpeed of base class (vehicle)

System.out.println("Maximum Speed: "

+ super.maxSpeed);

// Driver Program

class Test {

public static void main(String[] args)

Car small = new Car();

small.display();

Output
Maximum Speed: 120
In the above example, both the base class and subclass have a member
maxSpeed. We could access the maxSpeed of the base class in subclass
using super keyword.
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.

EXAMPLE 1

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
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.
To call the parent class method, we need to use super keyword.

EXAMPLE 2

// super keyword in java example

// superclass Person

class Person {
void message()

System.out.println("This is person class\n");

// Subclass Student

class Student extends Person {

void message()

System.out.println("This is student class");

// Note that display() is

// only in Student class

void display()

// will invoke or call current

// class message() method

message();

// will invoke or call parent

// class message() method

super.message();

}
}

// Driver Program

class Test {

public static void main(String args[])

Student s = new Student();

// calling display() of Student

s.display();

Output
This is student class
This is person class
In the above example, we have seen that if we only call
method message() then, the current class message() is invoked but with
the use of the super keyword, message() of the superclass could also be
invoked.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:

EXAMPLE 1

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}

Output:

animal is created
dog is created

Note: super () is added in each class constructor automatically by compiler if there is


no super () or this().
EXAMPLE 2
// Java Code to show use of
// super keyword with constructor

// superclass Person
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}

// subclass Student extending the Person class


class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}

// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor
In the above example, we have called the superclass constructor using
the keyword ‘super’ via subclass constructor.
EXAMPLE 3

class ParentClass {
public boolean isTrue() { return true; }
}

class ChildClass extends ParentClass {


public boolean isTrue()
{
// calls parent implementation of isTrue()
boolean parentResult = super.isTrue();
// negates the parent result
return !parentResult;
}
}

public class Main {


public static void main(String[] args)
{
ChildClass child = new ChildClass();
// calls child implementation
// of isTrue()
boolean result = child.isTrue();

// prints "false"
System.out.println(result);
}
}
Output
false

Another example of super keyword where super() is provided by the compiler


implicitly.

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

super example: real use


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. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
Output:

22. 1 ankit 45000

Example
Using super to call the superclass of Dog (subclass):
class Animal { // Superclass (parent)

public void animalSound() {

System.out.println("The animal makes a sound");

class Dog extends Animal { // Subclass (child)

public void animalSound() {

super.animalSound(); // Call the superclass method

System.out.println("The dog says: bow wow");

public class Main {

public static void main(String[] args) {

Animal myDog = new Dog(); // Create a Dog object

myDog.animalSound(); // Call the method on the Dog object

OUTPUT

The animal makes a sound


The dog says: bow wow

Advantages of Using Java Super Keyword


The super keyword in Java provides many advantages in object-oriented
programming are as follows:
 Enables reuse of code: Using the super keyword allows subclasses to
inherit functionality from their parent classes, which promotes the reuse
of code and reduces duplication.
 Supports polymorphism: Because subclasses can override methods
and access fields from their parent classes using super, polymorphism
is possible. This allows for more flexible and extensible code.
 Provides access to parent class behaviour: Subclasses can access
and use methods and fields defined in their parent classes through the
super keyword, which allows them to take advantage of existing
behaviour without having to reimplement it.
 Allows for customization of behaviour: By overriding methods and
using super to call the parent implementation, subclasses can
customize and extend the behaviour of their parent classes.
 Facilitates abstraction and encapsulation: The use of super
promotes encapsulation and abstraction by allowing subclasses to
focus on their behaviour while relying on the parent class to handle
lower-level details.
Important Points to Remember While Using “Java Super Keyword”
Here are some Important points that you need to take care of during using
super keywords in Java:
 Call to super() must be the first statement in the Derived(Student)
Class constructor because if you think about it, it makes sense that
the superclass has no knowledge of any subclass, so any initialization
it needs to perform is separate from and possibly prerequisite to any
initialization performed by the subclass. Therefore, it needs to
complete its execution first.
 If a constructor does not explicitly invoke a superclass constructor, the
Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the superclass does not have a no-
argument constructor, you will get a compile-time error. The
object does have such a constructor, so if the Object is the only
superclass, there is no problem.
 If a subclass constructor invokes a constructor of its superclass, either
explicitly or implicitly, you might think that a whole chain of constructors
is called, all the way back to the constructor of Object. This, in fact, is
the case. It is called constructor chaining.

Constructor Chaining In Java with Examples


Constructor chaining is the process of calling one constructor from
another constructor with respect to current object.
Constructor chaining can be done in two ways:
 Within same class: It can be done using this() keyword for
constructors in the same class
 From base class: by using super() keyword to call the constructor
from the base class.

Why do we need constructor chaining?


This process is used when we want to perform multiple tasks in a
single constructor rather than creating a code for each task in a
single constructor we create a separate constructor for each task
and make their chain which makes the program more readable.

// Java program to illustrate Constructor Chaining

// within same class Using this() keyword

class Temp

// default constructor 1

// default constructor will call another constructor

// using this keyword from same class

Temp()

// calls constructor 2

this(5);

System.out.println("The Default constructor");

// parameterized constructor 2

Temp(int x)

{
// calls constructor 3

this(5, 15);

System.out.println(x);

// parameterized constructor 3

Temp(int x, int y)

System.out.println(x * y);

public static void main(String args[])

// invokes default constructor first

new Temp();

Output:
75
5
The Default constructor
Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword
(constructor 3 in above example).
3. Constructor chaining can be achieved in any order.

What happens if we change the order of constructors?


Nothing, Constructor chaining can be achieved in any order

Constructor Chaining to other class using super() keyword :

// Java program to illustrate Constructor Chaining to

// other class using super() keyword

class Base

String name;

// constructor 1

Base()

this("");

System.out.println("No-argument constructor of" +

" base class");

// constructor 2

Base(String name)

this.name = name;
System.out.println("Calling parameterized constructor"

+ " of base");

class Derived extends Base

// constructor 3

Derived()

System.out.println("No-argument constructor " +

"of derived");

// parameterized constructor 4

Derived(String name)

// invokes base class constructor 2

super(name);

System.out.println("Calling parameterized " +

"constructor of derived");

}
public static void main(String args[])

// calls parameterized constructor 4

Derived obj = new Derived("test");

// Calls No-argument constructor

// Derived obj = new Derived();

Output:
Calling parameterized constructor of base
Calling parameterized constructor of derived
Note : Similar to constructor chaining in same class, super() should be
the first line of the constructor as super class’s constructor are invoked
before the sub class’s constructor.

Q1. What is super () and super keyword in Java?

Super() is a Java keyword used to call a superclass constructor. Super


accesses superclass members and maintains inheritance hierarchies.

Q2. Which is the super class of Java?

The Object class aka super class is at the top of the class hierarchy in
Java’s java.lang package. Every class, whether predefined or user-
defined, is a subclass of the Object class.

Q3. Why is Super important in Java?


super is essential in Java as it facilitates the access, initialization, and
management of relationships between superclasses and subclasses,
thereby promoting code reusability.

You might also like