Questions
Give examples showing how “super” and “this” are useful with inheritance in Java. Include examples of using “super” and “this” both as constructors and as variables.
1. Keywords
super: In a subclass, we can use keyword super to call the superclass instance methods, and its constructors. Specifically, if we override a superclass method, the subclass and the superclass will have a method with the same name and signatures. At this time, if we want to call the superclass method instead of the overridden method in the subclass, we can use the super.method() to achieve it. Besides, we can put super() or super(arguments) in the first line of the subclass constructor to call the superclass constructor (Seiter & Palmer, 2020).
this: The keyword this is a reference to the current object. We can use this() or this(arguments) to call other constructs in the same class. Besides, we can use the this.variable to distinguish an instance variable and a local parameter if they have the same name in a class (Seiter & Palmer, 2020).
2. Examples
2.1. Example of super as variable and constructor
Codes:
1 | public class Fruits { |
1 | public class Grapes extends Fruits { |
Outputs:
1 | Name: Grapes |
Explanation:
In the above example, I defined a superclass Fruits and used Grapes to extend it. In the subclass Grapes, I use the statement super(initName, initColor, initTaste) to call the Fruits’ constructor to initialize the instance variables: name, color, and taste. Besides, in the subclass Grapes’ toString() method, I use super.toString() to call the superclass Fruits’ toString() method and concatenation its return value with the variable specialFunction’s value as the grapes’ info.
2.2. Example of this as variable and constructor
Codes:
1 | public class Apples { |
Outputs:
1 | Name: Apple |
Explanation:
In the above Apple class, I defined three constructors: One with no parameter, one with two parameters, and one with three parameters. In the constructor with three parameters, I use the statement this(name,color) to call the two-parameter constructor. Besides, in this three-parameter constructor, I deliberately use the same name for parameter taste and instance variable taste. In order to distinguish these two tastes, we can use this.taste to represent the instance varibale taste, and taste to represent the parameter taste.
Word count: 679
References
1.Seiter, L. & Palmer, D. (2020). Introduction to Programming with Java.
https://runestone.academy/runestone/books/published/csjava/index.html