Tuesday, 3 February 2015

Java Constructors

If you have a class called, for example, Rectangle, you can add a method to it with the same name as the class. This method must have no return type, not even void. It is called a constructor. Here is an example:

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

The purpose of a constructor is to give default values to a class member when it is created. You can see what I mean below, where an instance of Rectangle is created. It automatically has a width of 2 and a height of 3:

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