Java programming: constructors in subclasses
Tutoring Java programming, there are so many interesting facets to encounter. The tutor talks about a constructor of a subclass and the word super.
Let’s imagine you write a subclass. Furthermore, let’s imagine the parent class (the superclass) has a detailed constructor. Can you assume that the subclass will simply inherit the parent’s constructor and default to its use? Apparently not.
My situation: I wrote a subclass of an abstract class that, while abstract, has a well-defined constructor. In the subclass I just defined the abstract functions from the parent. The compiler protested, citing a mismatch between the parameters required for the constructor versus those given. I looked up the problem.
Apparently, to a subclass, the compiler provides a default constructor with no arguments.
To instill the parent’s constructor in the subclass, one can declare a constructor in the subclass with the same parameters as those of the superclass’ constructor, then call super(parameter list).
Let’s imagine a parent class PC like so:
class PC{
String name;
String color;
this.name=name;
this.color=color;
}//end of constructor
}
Now, the subclass SC:
class SC extends PC{
super(name,color);
}//end constructor
}
From my observation, the code in the blue rectangles above is what will make the subclass take on the parent’s constructor.
Source:
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.