Constructor in Java

Constructor in Java is a special method used to initialize an object. It is automatically created in the constructor when the object is created.

Key points:
The constructor must have the same name as the class.
Return type (not void)
It is automatically created when the object is newly created.
You can have default and parameterized constructors.

Simple example:

class Car {
String model;
int year;
// constructor
Car(String m, int y) {
Model = m;
Year = y;
}
void display() {
System.out.println("Model: " + Model + ", Year: " + Year);
}
}

public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2022); // constructor comes here
myCar.display();
}
}

Output:

Model: Toyota, Year: 2022
 

Comments

Popular posts from this blog

Post GIS

What is GIS?

Spring Boot Application Properties and YAML Configuration