Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Super
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
When implementing inheritance, use the Java reserved word super to call a method in the superclass or to invoke the constructor of the superclass. Remember that private methods cannot be accessed by the subclass. Take a look below to see how super is used.
SuperExample.java
package exlcode;
public class SuperExample {
public static void main(String[] args) {
SuperTestTwo superTestTwo = new SuperTestTwo(10,20);
}
}
SuperTestOne.java
package exlcode;
public class SuperTestOne {
public int exampleVariableOne = 10;
public SuperTestOne(int parameterOne) {
this.exampleVariableOne = parameterOne;
}
public void print(){
System.out.println(exampleVariableOne);
}
}
SuperTestTwo.java
package exlcode;
public class SuperTestTwo extends SuperTestOne {
public SuperTestTwo(int parameterOne, int parameterTwo) {
super(parameterOne);
super.print();
}
}
The word super is usually used to call the constructor, but could also be used to call methods. When you start using inheritance in the future, you will most likely be using super more for invoking constructors of the superclass. In the code above, SuperTestTwo invokes the constructor of its superclass SuperTestOne and sets parameterOne directly from the superclass. Therefore, when the print() method is called in the SuperTestTwo class, it prints 10.
Remember that super(); has to be the first statement in the subclass' constructor. Otherwise, you will get a compile-time error. Also, if you extend a class without a zero-argument constructor, like SuperTestTwo above, make sure to use one of the superclass' constructors and have the same parameters. Another data type in the parameter would cause an error. But, if the constructor in the superclass has no arguments(parameters), Java will automatically call one for you in the subclass, so super(); will not be necessary in that case.