Wednesday, July 5, 2017

Calling a Constructor From a Constructor & Calling Constructors in Superclasses

Calling a Constructor From a Constructor

In Java it is possible to call a constructor from inside another constructor. When you call a constructor from inside another constructor, you use the this keyword to refer to the constructor. Here is an example of calling one constructor from within another constructor in Java:
public class Employee {

    private String firstName = null;
    private String lastName  = null;
    private int    birthYear = 0;

    public Employee(String first,
        String last,
        int    year   ) {

        firstName = first;
        lastName  = last;
        birthYear = year;
    }

    public Employee(String first, String last){
        this(first, last, -1);
    }
}
Notice the second constructor definition. Inside the body of the constructor you find this Java statement:
this(first, last, -1);
The this keyword followed by parentheses and parameters means that another constructor in the same Java class is being called. Which other constructor that is being called depends on what parameters you pass to the constructor call (inside the parentheses after the this keyword). In this example it is the first constructor in the class that is being called.

Calling Constructors in Superclasses

In Java a class can extend another class. When a class extends another class it is also said to "inherit" from the class it extends. The class that extends is called the subclass, and the class being extended is called the superclass. Inheritance is covered in more detail in my tutorial about inheritance in Java.
A class that extends another class does not inherit its constructors. However, the subclass must call a constructor in the superclass inside one of the subclass constructors!
Look at the following two Java classes. The class Car extends (inherits from) the class Vehicle.
public class Vehicle {
    private String regNo = null;

    public Vehicle(String no) {
        this.regNo = no;
    }
}
public class Car extends Vehicle {
    private String brand = null;

    public Car(String br, String no) {
        super(no);
        this.brand = br;
    }
}
Notice the constructor in the Car class. It calls the constructor in the superclass using this Java statement:
super(no);
Using the keyword super refers to the superclass of the class using the super keyword. When super keyword is followed by parentheses like it is here, it refers to a constructor in the superclass. In this case it refers to the constructor in the Vehicle class. Because Car extends Vehicle, the Car constructors must all call a constructor in the Vehicle.

@reference_1_jenkov.com
Java Constructors

No comments:

Post a Comment