Java Default Constructor

In this chapter you will learn:

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

Description

A default constructor is a constructor with no parameters.

Syntax

Syntax for Java Default Constructor


class ClassName{/*from  w  ww .j  a v a 2 s.co m*/

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

Example

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

 
class Rectangle {
  double width;/* ww w  .j  av a 2  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);

  }
}

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  ww  . j av  a2  s.  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:

Next chapter...

What you will learn in the next chapter:

  1. How to pass in value with parameters for constructors
  2. Syntax for Java Constructor Parameters
  3. Example - Java Constructor Parameters
  4. How to declare object parameters for constructors