Constructors

Constructor

A constructor is used to provide or assign an initial value

Instantiation

A constructor, optional special method, is called when an instance is being created in the process called Instantiation

No Constructor

When there is no constructor the interpreter defines one, and assigns default values to all fields:

  • Numeric - 0
  • Character - \u0000 Unicode for empty character
  • Boolean - false
  • Object - null

Syntax

A constructor can be defined by the following:

  1. public - modifier
  2. name - class name (needs to be the same name as the class)
  3. parenthesis - enclosing parameter list
  4. parameter list - the same as in methods
public LightBulb(String init_color, int init_watts){
	isPowered = false;
	color = init_color;
	watts = init_watts;
}

Note

Constructors are also methods except it requires no return type

this Keyword

  • this keyword is used when some of the methods uses the same variable names as the attributes/fields.
  • The this keyword is used to reference the attribute/field in the class.

Example

public class Person{
  private String name
  public void ChangeName(String name){
  	this.name = name;
  }
}