Java Class Constructors

In this chapter you will learn:

  1. What is Java class constructor
  2. Syntax for Java Class Constructors
  3. Example - Java Class Constructors

Description

A constructor initializes an object during object creation when using new operator.

Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.

Syntax

It has the same name as the class. Constructors have no return type, not even void.


class ClassName{// ww w.ja  v  a 2  s  .  c  o  m

   ClassName(parameter list){ // constructor
    ...
   }
}

Example

In the following code the Rectangle class in the following uses a constructor to set the dimensions:

 
class Rectangle {
  double width;/*  w ww .  j a  va2  s  . c  o  m*/
  double height;

  Rectangle() {
    width = 10;
    height = 10;
  }

  double area() {
    return width * height;
  }
}

public class Main {
  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle();
    double area;
    area = mybox1.area();
    System.out.println("Area is " + area);

  }
}

When this program is run, it generates the following results:

Next chapter...

What you will learn in the next chapter:

  1. What is Java Default Constructor
  2. Syntax for Java Default Constructor
  3. Example - Java Default Constructor
  4. Example - auto-added default constructor