Index


Introduzione

  • A constructor in Java is a “special” method that is invoked when an object of the class is created.
  • Inizializzano i campi dello stato iniziale di un oggetto

Important Notes on Java Constructors

  • Constructors are invoked implicitly when you instantiate objects.
  • The two rules for creating a constructor are:
    1. The name of the constructor should be the same as the class.
    2. A Java constructor must not have a return type.
  • If a class doesn’t have a constructor, the Java compiler automatically creates a default constructor during run-time. The default constructor initializes instance variables with default values. For example, the int variable will be initialized to 0

Types of Constructor

In Java, constructors can be divided into three types:


No-Arg Constructor

Similar to methods, a Java constructor may or may not have any parameters (arguments).

public class Counter {
	// Costruttore
	public Counter() {
		valore = 0;
	}
}

If a constructor does not accept any parameters, it is known as a no-argument constructor. For example,


Parameterised Constructor

A Java constructor can also accept one or more parameters.

class Main {
 
  String languages;
 
  // constructor accepting single value
  Main(String lang) {
    languages = lang;
  }
 
  public static void main(String[] args) {
 
    // call constructor by passing a single value
    Main obj1 = new Main("Java");
    Main obj2 = new Main("Python");
    Main obj3 = new Main("C");
  }
}

Default Constructor

If we do not create any constructor, the Java compiler automatically creates a no-arg constructor during the execution of the program.

class Main {
 
  int a;
  boolean b;
 
  public static void main(String[] args) {
 
    // calls default constructor
    Main obj = new Main();
 
    System.out.println("Default Value:");
    System.out.println("a = " + obj.a);    // output: 0
    System.out.println("b = " + obj.b);    // output: false
  }

The default constructor initialises any uninitialised instance variables with default values.

TypeDefault Value
booleanfalse
byte0
short0
int0
long0L
char\u0000
float0.0f
double0.0d
objectReference null

Constructor Overloading

Similar to Java method overloading, we can also create two or more constructors with different parameters. This is called constructor overloading.

Esempio più metodi costruttori nella stessa classe:

public Counter(){
	value = 0;
}
 
public Counter(int initaliaValue){
	value = initialValue;
}

How to “call” a constructor

I costruttori vengono “chiamati” utilizzando new NomeCostruttore()

static public void main(String[] args)
{
	Counter contatore1 = new Counter();
	Counter contatore2 = new Counter(42);
}