This book is now obsolete Please use CSAwesome instead.
11.11. Inheritance and Constructors¶
How do you initialize inherited private fields if you don’t have direct access to them in the subclass? In Java you can put a call to the parent constructor using the keyword
super as the first line in a subclass constructor to initialize inherited fields. See the constructor in Employee below for an example.
super(theName) in the
Employee constructor will call the constructor that takes a
String object in the
Person class to set the name.
If a class has no constructor in Java, the compiler will add a no-argument constructor. A no-argument constructor is one that doesn’t have any parameters.
The code above is a no-argument constructor for the
Person class. Remember that constructors don’t have a return type and the constructor name must match the class name.
If a subclass has no call to
a superclass constructor using
super as the first line in a subclass constructor then the compiler will automatically add a
super() call as the first line in a constructor. So, be sure to provide no-argument constructors in parent classes or be sure to use an explicit call to
super as the first line in the constructors of subclasses.
You can step through this code in the Java Visualizer by clicking on the following link Constructor Test1.
You can step through this code using the Java Visualizer by clicking the following link Named Point.