Java - Constructor

> Procedural Languages > Java

1 - About

Object - Constructor in Java.

A class contains constructors that are invoked to create objects from the class blueprint.

Constructor declarations look like method declarations—except that:

  • they use the name of the class
  • they have no return type.

A constructor is not obligatory. See Default.

You can use access modifiers in a constructor's declaration to control which other classes can call the constructor. If another class cannot call a MyClass constructor, it cannot directly create MyClass objects.

Advertising

3 - Type

3.1 - With Parameter

public Bicycle(int startCadence, int startSpeed, int startGear) {
	gear = startGear;
	cadence = startCadence;
	speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called in an other class by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

3.2 - No-argument

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() {
	gear = 1;
	cadence = 10;
	speed = 0;
}

The following code invokes the no-argument constructor to create a new Bicycle object called yourBike.

Bicycle yourBike = new Bicycle(); 

Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.

3.3 - Default

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

This default constructor will call the no-argument constructor of the superclass.

In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does.

If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

Advertising
lang/java/constructor.txt · Last modified: 2017/09/17 17:24 by gerardnico