Child Classes

A child class is more specific version of a parent class. (A child class may also be called a sub class or a derived class.) It retains the same features of the parent class, but adds more detail/functionality. For example, a Student class would retain the name and age from the Person class, but would add more features unique to students – major and gpa, for example.

To create a child class, you need to extend the parent class. Here’s the format:

public class ChildName extends ParentName 
{
    //normal class stuff
}

The child class automatically inherits any public or protected variables and methods from the parent class. So if I do:

public class Student extends Person 
{

}

Then the Student class inherits the name variable, the age variable, and the print method. This means that we can pretend as if name, age, and print() are in the same class as Student – we automatically get to use them, but we don’t have to write them again. So, we only need to declare the major and gpa variables:

public class Student extends Person 
{
    private String major;
    private double gpa;
}

Next comes the constructor of the child class. We could simply do:

public Student(String n, int a, string m, double g) 
{
    this.name = n; //Student inherits name
    this.age = a; //Student inherits age
    this.major = m;
    this.gpa = g;
}

However, if you try this, the Student class will not compile. The reason for this is the compiler will try to call the parent constructor (Person) before executing the code in the Student constructor. It will try to call Person(), but of course Person does not have a no-argument constructor. To deal with this, we need to call the parent constructor ourselves. Here’s how:

super(n, a)

The super keyword refers to the parent object (similarly to “this””. This calls the Person constructor and passes the name and age. Of course, the Person constructor initializes the name and age variables itself, so now we don’t have to. Here’s what the Student constructor looks like now:

public Student(String n, int a, String m, double g) 
{
    super(n, a);
    this.major = m;
    this.gpa = g;
}

Always include a call to super on the first line of the child constructor.