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:
- The name of the constructor should be the same as the class.
- 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 to0
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).
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.
Default Constructor
If we do not create any constructor, the Java compiler automatically creates a no-arg constructor during the execution of the program.
The default constructor initialises any uninitialised instance variables with default values.
Type | Default Value |
---|---|
boolean | false |
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
char | \u0000 |
float | 0.0f |
double | 0.0d |
object | Reference 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:
How to “call” a constructor
I costruttori vengono “chiamati” utilizzando new NomeCostruttore()