In Java, the super and super() keywords are used in different contexts and serve different purposes:
- super:
- A reference variable that refers to parent class objects.
- Can be used to call parent class variables and methods.
- Can be used to access specific variables of a superclass.
- Can be used to invoke any accessible method in the superclass.
- super():
- A reference variable that refers to parent class constructors.
- Can be used to call parent class constructors only.
- Must be the first statement in the derived class constructor.
- Used to initialize superclass variables when there is no constructor in the subclass.
In summary, super is used to refer to parent class objects, variables, and methods, while super() is used to call parent class constructors, typically during the construction of a subclass object.
Comparative Table: this vs super in Java
The this and super keywords in Java are used within constructors to call other constructors in the same class or in the superclass. Here is a table summarizing their differences:
| Feature | this |
super |
|---|---|---|
| Purpose | Calls another constructor within the same class | Calls a constructor in the superclass of the current class |
| Representation | Represents the current instance of the class | Represents the current instance of the parent class |
| Accessibility | Accesses methods and fields of the current class | Accesses methods and fields of the parent class |
| Static Context | Can be used from a static context (e.g., System.out.println(this.x)) |
Cannot be used from a static context (e.g., System.out.println(super.x) will cause a compile-time error) |
Some examples of this and super usage include:
- Using
thisto call another constructor within the same class:
class MyClass {
private int value;
public MyClass() {
this(5);
}
public MyClass(int value) {
this.value = value;
}
}
- Using
superto call a superclass constructor:
class SubClass extends SuperClass {
public SubClass() {
super();
}
}
Remember that this and super cannot be used from a static context, since they represent instance members and methods, not static ones.
Read more
- this vs super in Java
- Overloading vs Overriding in Java
- Java vs Spring
- Superclass vs Subclass
- static vs final in Java
- Java vs Oracle
- Android vs Java
- Java vs C++
- Java5 vs Java6
- Wrapper Class vs Primitive Type in Java
- Java vs JavaScript
- final finally vs finalize in Java
- Inheritance vs Interface in Java
- Package vs Interface in Java
- equals vs hashCode in Java
- throw vs throws in Java
- String StringBuffer vs StringBuilder in Java
- Java vs J2EE
- This vs These
- Java vs C language