OBJECT-ORIENTED PROGRAMMING
Java constructors
A constructor is a special class member called automatically when a new object is created. It sets the object's initial attribute values and prepares the object for use.
What is a constructor?
A constructor resembles a method but has two important rules:
- its name must exactly match the class name;
- no return type appears before its name, not even
void.
public class Knyga {
String busena;
Knyga() {
busena = "Neskaityta";
}
public static void main(String[] args) {
Knyga knyga = new Knyga();
System.out.println(knyga.busena);
}
}Neskaityta
- The constructor name
Knygaexactly matches the class name. - There is no
voidor other return type before the constructor name. - The expression
new Knyga()creates a new object and automatically runs the constructor. - The constructor sets the object's attribute
busenato the text Neskaityta. - After the object is created,
println()displays the initial state that has already been set.
A constructor with parameters
Parameters let you supply the required initial values when creating an object:
public class Knyga {
String pavadinimas;
int puslapiuSkaicius;
Knyga(String pavadinimas, int puslapiuSkaicius) {
this.pavadinimas = pavadinimas;
this.puslapiuSkaicius = puslapiuSkaicius;
}
public static void main(String[] args) {
Knyga knyga = new Knyga("Mažasis princas", 96);
System.out.println(knyga.pavadinimas);
System.out.println(knyga.puslapiuSkaicius);
}
}Mažasis princas
96
- The constructor expects two pieces of data: the book title and page count.
- The arguments passed when creating the object are Mažasis princas and
96. this .pavadinimasmeans the attribute of the object being created, while the right-handpavadinimasis the parameter.- Both supplied values are thus stored in the new object.
- After the constructor finishes, the prepared object's attributes can be displayed in the console.
this refers to the object being created.this.pavadinimas is the object's attribute, while the right-hand pavadinimas is the constructor parameter.
Different objects from one constructor
The same constructor can initialize many objects using different arguments:
public class Knyga {
String pavadinimas;
int puslapiuSkaicius;
Knyga(String pavadinimas, int puslapiuSkaicius) {
this.pavadinimas = pavadinimas;
this.puslapiuSkaicius = puslapiuSkaicius;
}
public static void main(String[] args) {
Knyga pirma = new Knyga("Mažasis princas", 96);
Knyga antra = new Knyga("Pepė Ilgakojinė", 160);
System.out.println(pirma.pavadinimas + ": " + pirma.puslapiuSkaicius);
System.out.println(antra.pavadinimas + ": " + antra.puslapiuSkaicius);
}
}Mažasis princas: 96
Pepė Ilgakojinė: 160
- The first
new Knyga(...)call creates an object with the title Mažasis princas. - The second call creates another object with the title Pepė Ilgakojinė.
- Both calls run the same constructor but pass different arguments.
- Each object stores its own title and page count.
- The console therefore shows two different books.
Multiple constructors in a class
A class can have multiple constructors if their parameter counts or types differ. This is called
public class Knyga {
String pavadinimas;
int puslapiuSkaicius;
Knyga(String pavadinimas) {
this(pavadinimas, 0);
}
Knyga(String pavadinimas, int puslapiuSkaicius) {
this.pavadinimas = pavadinimas;
this.puslapiuSkaicius = puslapiuSkaicius;
}
public static void main(String[] args) {
Knyga bePuslapiu = new Knyga("Užrašų knygelė");
Knyga romanas = new Knyga("Mažasis princas", 96);
System.out.println(bePuslapiu.pavadinimas + ": " + bePuslapiu.puslapiuSkaicius);
System.out.println(romanas.pavadinimas + ": " + romanas.puslapiuSkaicius);
}
}Užrašų knygelė: 0
Mažasis princas: 96
- The first constructor accepts only the book title.
- It uses
this(pavadinimas, 0)to call the second constructor in the same class, passing a default page count of0. - The second constructor accepts both the title and the actual page count.
- Java selects a constructor based on the number of arguments passed.
this(...)call must be the first constructor statement.
The default constructor
If a class defines no constructors, the Java compiler supplies a default no-argument constructor:
public class Knyga {
String pavadinimas;
public static void main(String[] args) {
Knyga knyga = new Knyga();
System.out.println(knyga.pavadinimas);
}
}null
- The class
Knygadefines no constructors. - The Java compiler automatically supplies an empty no-argument constructor.
- This makes the expression
new Knyga()valid. - The attribute
pavadinimaswas not assigned a value explicitly, so it receives the default object reference value,null. println()displays in the console null.
If you still need to create objects without arguments, declare that constructor yourself.
A constructor and a method
| Property | Constructor | The method |
|---|---|---|
| Name | Matches the class | Describes the action performed |
| Return type | Not written | Required, for example, void or int |
| Invocation | Automatically with new | Called by name |
| Main purpose | Initialize an object | Perform an object or class action |
Guidelines for using constructors
- After the constructor finishes, the object should be in a valid, consistent state.
- Pass required data as constructor parameters.
- Avoid long constructors or ones that perform many external operations.
- Centralize initialization shared by several constructors using
this(...).