Java Constructors

🔹 Java Constructors

A constructor in Java is a special method used to initialize objects. It is called automatically when an object is created.


✅ 1. Key Features of Constructors

  • Same name as the class

  • No return type (not even void)

  • Can have parameters

  • Used to initialize instance variables

  • Can be overloaded


✅ 2. Types of Constructors

  1. Default Constructor – No parameters; provided automatically if no constructor is defined.

  2. Parameterized Constructor – Takes parameters to initialize an object with specific values.

  3. No-Arg Constructor – A user-defined constructor without parameters (similar to default).


✅ 3. Example 1: Default Constructor

class Car {
String brand;
int year;
// Default constructor
Car() {
brand = “Unknown”;
year = 0;
}

void display() {
System.out.println(“Brand: “ + brand + “, Year: “ + year);
}
}

public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Default constructor called
car1.display();
}
}

📌 Output:

Brand: Unknown, Year: 0

✅ 4. Example 2: Parameterized Constructor

class Car {
String brand;
int year;
// Parameterized constructor
Car(String b, int y) {
brand = b;
year = y;
}

void display() {
System.out.println(“Brand: “ + brand + “, Year: “ + year);
}
}

public class Main {
public static void main(String[] args) {
Car car1 = new Car(“Toyota”, 2022);
Car car2 = new Car(“Honda”, 2023);

car1.display();
car2.display();
}
}

📌 Output:

Brand: Toyota, Year: 2022
Brand: Honda, Year: 2023

✅ 5. Example 3: Constructor Overloading

class Rectangle {
int length, width;
// No-arg constructor
Rectangle() {
length = 0;
width = 0;
}

// Parameterized constructor
Rectangle(int l, int w) {
length = l;
width = w;
}

int area() {
return length * width;
}
}

public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(5, 10);

System.out.println(“Area of r1 = “ + r1.area());
System.out.println(“Area of r2 = “ + r2.area());
}
}

📌 Output:

Area of r1 = 0
Area of r2 = 50

✅ 6. Key Points About Constructors

  • Constructor name must match the class name.

  • No return type, not even void.

  • Can be overloaded to provide multiple ways of initializing objects.

  • Automatically called when an object is created.

  • this keyword can be used to refer to current object or call another constructor.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *