0% found this document useful (0 votes)
3 views3 pages

Java Constructors Explanation

A constructor is a special method in a class that initializes objects upon creation and must have the same name as the class without a return type. There are three types of constructors: default (no parameters), parameterized (with parameters), and constructor overloading (multiple constructors). Constructors help in initializing values, making code cleaner, and are widely used in real-world applications.

Uploaded by

eliassannu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Java Constructors Explanation

A constructor is a special method in a class that initializes objects upon creation and must have the same name as the class without a return type. There are three types of constructors: default (no parameters), parameterized (with parameters), and constructor overloading (multiple constructors). Constructors help in initializing values, making code cleaner, and are widely used in real-world applications.

Uploaded by

eliassannu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Java Constructors - Easy Explanation

What is a Constructor?
----------------------
A constructor is a special method in a class that is automatically called when you create an object of
the class.

Rules of Constructors:
- The constructor name must be the same as the class name.
- Constructors do not have a return type.
- They are used to initialize objects.

Types of Constructors:
----------------------

1. Default Constructor (no parameters)


Example:
class Car {
Car() {
System.out.println("Car is created");
}

public static void main(String[] args) {


Car myCar = new Car();
}
}
Output: Car is created

2. Parameterized Constructor (with parameters)


Example:
class Car {
String model;

Car(String carModel) {
model = carModel;
System.out.println("Car model is: " + model);
}

public static void main(String[] args) {


Car myCar = new Car("BMW");
}
}
Output: Car model is: BMW

3. Constructor Overloading (multiple constructors)


Example:
class Car {
Car() {
System.out.println("Default Car");
}

Car(String model) {
System.out.println("Model: " + model);
}

Car(String model, int year) {


System.out.println("Model: " + model + ", Year: " + year);
}

public static void main(String[] args) {


new Car();
new Car("Audi");
new Car("Mercedes", 2024);
}
}
Output:
Default Car
Model: Audi
Model: Mercedes, Year: 2024

Why use Constructors?


---------------------
- To initialize values at object creation
- To make code cleaner and automatic
- Used heavily in real-world applications

You might also like