Wednesday 4 February 2015

Overloaded Java Constructors

The example below shows a class with an overloaded constructor:

Java > cat Rectangle.java
class Rectangle
  {
  double width;
  double height;
  Rectangle()
    {
    width = 2;
    height = 3;
    }
  Rectangle(double w, double h)
    {
    width = w;
    height = h;
    }
  }
Java > javac Rectangle.java
Java >

If you have a class like this, when you create members, you have a choice. You can accept the default settings or you can override them by supplying parameters. In the example below, r1 takes the default settings whereas r2 uses parameters to change the width to 4 and the height to 5:

Java > cat RectangleExample.java
public class RectangleExample
  {
  public static void main(String args[])
    {
    Rectangle r1 = new Rectangle();
    System.out.println("r1 width = " + r1.width);
    System.out.println("r1 height = " + r1.height);
    Rectangle r2 = new Rectangle(4,5);
    System.out.println("r2 width = " + r2.width);
    System.out.println("r2 height = " + r2.height);
    }
  }
Java > javac RectangleExample.java
Java > java RectangleExample
r1 width = 2.0
r1 height = 3.0
r2 width = 4.0
r2 height = 5.0
Java >