0% found this document useful (0 votes)
2 views2 pages

Java Constructors Explained

The document explains constructors in Java, which are special methods called when an object is created. It provides examples of both default and parameterized constructors using a 'Car' class. The default constructor initializes the brand to 'Toyota' and year to 2025, while the parameterized constructor allows setting custom values for brand and year.

Uploaded by

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

Java Constructors Explained

The document explains constructors in Java, which are special methods called when an object is created. It provides examples of both default and parameterized constructors using a 'Car' class. The default constructor initializes the brand to 'Toyota' and year to 2025, while the parameterized constructor allows setting custom values for brand and year.

Uploaded by

Devi Vara Prasad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Constructors and Constructors with Arguments in Java

1. Constructors in Java
A constructor is a special method in a class that is automatically called when an object is
created. It has the same name as the class and does not have a return type.

Default Constructor Example


class Car {
String brand;
int year;

Car() {
brand = "Toyota";
year = 2025;
[Link]("Default Constructor Called");
}
}

public class Main {


public static void main(String[] args) {
Car c1 = new Car();
[Link]([Link] + " - " + [Link]);
}
}

2. Parameterized Constructor Example


class Car {
String brand;
int year;

Car(String b, int y) {
brand = b;
year = y;
[Link]("Parameterized Constructor Called");
}
}

public class Main {


public static void main(String[] args) {
Car c1 = new Car("Honda", 2022);
Car c2 = new Car("Hyundai", 2024);
[Link]([Link] + " - " + [Link]);
[Link]([Link] + " - " + [Link]);
}
}

You might also like