DEV Community

Rahul kumar
Rahul kumar

Posted on

Power of super in Java

Java

Java is a High Level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.

Inheritance

In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation. Also defined as deriving new classes from existing ones such as super class or base class and then forming them into a hierarchy of classes.

Subclass and Superclass

In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

  • subclass (child) - the class that inherits from another class
  • superclass (parent) - the class being inherited from To inherit from a class, use the extends keyword.

super keyword

The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

Uses

Suppose you have a class A which have a member int top. You have another class B which inherits A and it also has a member top. Now, if you are initiating an instance of B and you want to get the top member of A from B instance. Do you think you can get this without super?

Let's see:

class A{
    int a;
    int top=90;
    A(int a){
        this.a = a;
    }
}
class B extends A{
    int b;
    int top = 40;
    B(int a, int b){
        super(a);
        this.b = b;
    }
}
Enter fullscreen mode Exit fullscreen mode

You have the class A and B. Let's create an object.

B obj = new B(4,5);

obj.a // 4
obj.b // 5
obj.top // 40
Enter fullscreen mode Exit fullscreen mode

Now, you want to get the top member of A. For this you need to use super keyword.

Modify B as needed

class B extends A{
    int b;
    int top = 40;
    B(int a, int b){
        super(a);
        this.b = b;
    }

    int getATop() {
        return super.top;
    }
}
Enter fullscreen mode Exit fullscreen mode

Call the member:

B obj = new B(4,5);
obj.top // 40
obj.getATop() // 90
Enter fullscreen mode Exit fullscreen mode

Note

  • super can access members from any level of hierarchy
  • if inside hierarchy any member or method overriden by any class, then calling super will get the member or method from the class just one level up.

Thanku

Top comments (2)

Collapse
 
weirdguppy1 profile image
weirdguppy1

Great article!

Collapse
 
ats1999 profile image
Rahul kumar

thanku