Java Fundamentals  «Prev  Next»
Lesson 3 Using constructors
ObjectiveProvide additional constructors for a class.

Using Java Constructors

To perform special initialization when an object is created, you can define super constructors for your class.

Super Constructors

There are some situations where you might want a class's constructor to call the constructor of its parent class. Java supports a special method named super() that represents a parent class's constructor. As an example, the default Lion constructor could call the default Predator constructor like this:

public Lion() {
  super();
  Lion(100, 15, false, Color.yellow);
}

In the following example, two constructors are defined for the Circle class:
class Circle {
  double radius;
  Circle() {
    this(1.0);
  }
  Circle(double radius) {
    this.radius = radius;
  }
  double area() {
    return Math.PI * radius * radius;
  }
}
class CircleTest {
  public static void main(String[] args) {
    Circle c1 = new Circle();
    Circle c2 = new Circle(7.0);
    System.out.println(c1.area());
    System.out.println(c2.area());
  }
}

The first circle created, c1, uses the first constructor to create a circle with a default radius of 1.0. The second circle, c2, uses the second constructor so that it can provide a specific radius for the circle.
In Java, you can call one constructor from another using the this keyword. Notice that the first constructor of the Circle class is calling the second constructor to initialize the radius of the circle to 1.0. Java's this keyword can also be used to reference instance variables from within an instance method. The second constructor, for example, uses the this keyword to differentiate the parameter radius that is passed to the constructor from the instance variable radius.

Add Constructor - Exercise

In this exercise, you will add a constructor to the RightTriangle class.
Add Constructor - Exercise