Java Default Constructor

Description

A default constructor is a constructor with no parameters.

Syntax

Syntax for Java Default Constructor


class ClassName{//from w ww  .  j  av a  2  s .c  o m

   ClassName(){ // default constructor
    ...
   }
}

Example

In the following code the constructor Rectangle() is the default constructor.

 
class Rectangle {
  double width;//from   w w  w .j a  va 2  s.c  om
  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);

  }
}

If you don't declare a default constructor the Java compiler will add one for you. When you call the default constructor added by Java compiler the class member variables are initialized by default value. If you do provide a default constructor the Java compiler would not insert one for you.

The code above generates the following result.

Example 2

In the following code we removes the default constructor from class Rectangle. When we compile the class Java compiler adds the default constructor for us so we can still construct a Rectangle object by calling the default constructor. But the value of width and height would be initialized to 0.0.

 
class Rectangle {
  double width;/* w w  w  .ja va  2s.  c o m*/
  double height;

  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);

  }
}

The output:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures