Sub topic 10
Subclass Construction and Superclass Constructors
A Java class can build on another class. The new class gets useful features from the existing one and can add its own.
A class is a definition for objects. An object is a value created from a class. For example, an Employee object might have a name and an employee ID.
When one class builds on another, Java calls this inheritance. The existing class is the superclass, and the class that builds on it is the subclass. A subclass object also has the features it inherits from its superclass, as long as access rules allow them to be used.
A constructor is a special part of a class that runs when an object is created. When you create a subclass object, Java also runs a superclass constructor. This chapter shows how to choose that constructor and pass information to it.
A person and an employee
An employee is a kind of person. Both have a name, but an employee also has an ID. We can put the shared name in Person and the extra ID in Employee.
A field is a variable that belongs to an object. A method is a named set of instructions that can return a result or perform an action.
Save the following code as Main.java:
class Person {
private final String name;
Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Employee extends Person {
private final int employeeId;
Employee(String name, int employeeId) {
super(name);
this.employeeId = employeeId;
}
public int getEmployeeId() {
return employeeId;
}
}
public class Main {
public static void main(String[] args) {
Employee employee = new Employee("Mina", 42);
System.out.println(employee.getName());
System.out.println(employee.getEmployeeId());
}
}Run it from the directory containing Main.java:
javac Main.java
java MainThe output is:
Mina
42The javac command compiles the code. Compiling means checking and translating the source code into a form Java can run. The java command then runs the program.
Read the class definitions
The words extends Person make Employee a subclass of Person. The employee has the name stored by Person and the ID stored by Employee.
The fields use private, which means code outside the class cannot access them directly. They also use final, which means each field can be assigned only once.
The methods use public, which makes them available to code that can access their classes. The Employee object can use getName() because it inherits that public method from Person. It can also use its own getEmployeeId() method.
There is one Employee object, not a separate Person object next to it. That employee object includes the state and behavior it gets from Person.
Pass values to the superclass
Look at the Employee constructor:
class Person {
private final String name;
Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Employee extends Person {
private final int employeeId;
Employee(String name, int employeeId) {
super(name);
this.employeeId = employeeId;
}
public int getEmployeeId() {
return employeeId;
}
}
public class ConstructorExample {
public static void main(String[] args) {
Employee employee = new Employee("Mina", 42);
System.out.println(employee.getName() + ": " + employee.getEmployeeId());
}
}This is a separate complete program. To run it, save it as ConstructorExample.java, then use javac ConstructorExample.java and java ConstructorExample.
A parameter is a variable named in a method or constructor definition. Here, name and employeeId are parameters of the Employee constructor. An argument is a value supplied in a call. In new Employee("Mina", 42), "Mina" and 42 are arguments.
The call super(name) passes the name to a Person constructor. Java chooses the constructor whose parameters match the arguments. Here, it chooses Person(String name).
The word this refers to the current object. In this.employeeId = employeeId, the part after the dot is the object's field. The name on the right is the parameter. The assignment stores the parameter's value in the field.
The constructor call has this path:
For code that works across Java versions, put super(...) as the first statement in the constructor body. Java 25 and later allow some statements before it under special restrictions, but the examples in this chapter use the simpler form.
Why not set the name directly?
The name field is private in Person. That protects it from direct access by code in other classes, including Employee.
So Employee should not try to assign this.name. Instead, it passes the name to Person with super(name). The Person constructor can assign its own private field.
The same rule does not stop an employee from using getName(). That method is public, and the method itself reads the private field from inside Person.
What if you leave out `super`?
If a constructor does not call either super(...) or another constructor with this(...), Java inserts a call to super() for you. This call has no arguments, so it needs an accessible superclass constructor with no parameters.
The following program works because Vehicle has such a constructor. Save it as ImplicitSuperDemo.java:
class Vehicle {
Vehicle() {
System.out.println("Vehicle constructor");
}
}
class Bicycle extends Vehicle {
Bicycle() {
System.out.println("Bicycle constructor");
}
}
public class ImplicitSuperDemo {
public static void main(String[] args) {
Bicycle bicycle = new Bicycle();
}
}Compile and run it:
javac ImplicitSuperDemo.java
java ImplicitSuperDemoIt prints:
Vehicle constructor
Bicycle constructorThe Bicycle constructor does not show a super() call, but Java supplies one. The Vehicle constructor runs before the remaining statement in the Bicycle constructor.
Now consider the earlier Person example. It declares Person(String name), but it does not declare Person(). If you remove super(name) from the Employee constructor, Java tries to insert super(). The code will not compile because there is no matching Person() constructor.
Constructors are not inherited
An Employee inherits accessible methods from Person, but it does not inherit Person constructors.
For example, Person has a constructor that accepts one String. That alone does not make new Employee("Mina") valid. The original Employee class only declares a constructor that accepts a String and an int.
You can add another Employee constructor if creating an employee with only a name is useful. Constructor overloading means declaring more than one constructor in a class, with different parameter lists.
The following separate program gives Employee two constructors. Save it as OverloadDemo.java:
class Person {
private final String name;
Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Employee extends Person {
private final int employeeId;
Employee(String name) {
this(name, 0);
}
Employee(String name, int employeeId) {
super(name);
this.employeeId = employeeId;
}
public int getEmployeeId() {
return employeeId;
}
}
public class OverloadDemo {
public static void main(String[] args) {
Employee employee = new Employee("Mina");
System.out.println(employee.getName());
System.out.println(employee.getEmployeeId());
}
}Run javac OverloadDemo.java and then java OverloadDemo. It prints Mina and 0 on separate lines.
The call this(name, 0) chooses another constructor in the same class. That constructor calls super(name). So the one-argument Employee constructor still leads to a Person constructor.
In these examples, a constructor starts with either a this(...) call or a super(...) call, not both. If it calls this(...), the chosen constructor is responsible for continuing the chain.
Common mistakes
- Calling a superclass constructor that does not exist. Match the number and types of arguments to an accessible superclass constructor.
- Forgetting an explicit
super(...). If the superclass has no accessible no-argument constructor, the insertedsuper()cannot work. - Trying to use a private superclass field directly. Pass its value to the superclass constructor or use an available method.
- Expecting superclass constructors to become subclass constructors. Declare each subclass constructor you want callers to use.
- Expecting Java to add a no-argument constructor after you declare another constructor. Java supplies a default no-argument constructor only when the class declares no constructors. Its superclass must still have an accessible no-argument constructor.
Practice
Exercise
Person has only Person(String name). Employee extends Person and declares Employee(String name), but its constructor body is empty. Why does the code fail to compile, and how can you fix it?
Show answer
Java inserts super(), but Person has no no-argument constructor. Put super(name) in the Employee constructor to call Person(String name).
Exercise
In the overloaded Employee example, what constructor calls occur for new Employee("Mina")?
Show answer
Employee(String name) calls Employee(String name, int employeeId) with this(name, 0). That constructor calls Person(String name) with super(name).