What does the super keyword represents and where can it be used? Give an example
ID: 674417 • Letter: W
Question
What does the super keyword represents and where can it be used? Give an example of a superclass and subclass. Be sure to make all the instances variables of the super class private. Include at least one constructor in each class and ensure that the constructor of the subclass calls the constructor of the superclass. Also include a toString method in both classes that returns the values of the instance variables with appropriate labels. Ensure that the toString method of subclass calls the toString method of the superclass so that the string returned contains the values of all the inherited instance variables.
Explanation / Answer
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:
Here is a subclass, called Subclass, that overrides printMethod():
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
super Usage:
1) super.<variable_name> refers to the variable of variable of parent class.
2) super() invokes the constructor of immediate parent class.
3) super.<method_name> refers to the method of parent class.
public class Class1{
private String a = "1";
private String b = "2";
public Class1(){
toStringg();
}
private void toStringg(){
System.out.println("a: "+ a + "b: " + b);
}
}
public class Class2 extends Class1{
private String a = "3";
private String b = "4";
public Class2(){
super(); //This will call the default constructor of Class1, which in turn will call the toString method from Class1
}
private void toStringg(){
System.out.println("a: "+ a + "b: " + b);
}
public static void main(String[] args){
Class2 class2 = new Class2();
class2.toStringg(); // This will call the toString method from Class2
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.