Java constructor
Created By: chatGPT
Constructors in Java are special methods that are called when an object is instantiated. They have the same name as the class and do not have a return type. Constructors are mainly used to initialize the object's properties or provide default values. There are two types of constructors: no-argument constructors and parameterized constructors.
public class Car {
String color;
String model;
// No-argument constructor
public Car() {
color = "Red";
model = "Sedan";
}
// Parameterized constructor
public Car(String color, String model) {
this.color = color;
this.model = model;
}
}
public class Main {
public static void main(String[] args) {
// Using no-argument constructor
Car car1 = new Car();
System.out.println("Car1 - Color: " + car1.color + ", Model: " + car1.model);
// Using parameterized constructor
Car car2 = new Car("Blue", "SUV");
System.out.println("Car2 - Color: " + car2.color + ", Model: " + car2.model);
}
}
When you create an object using the no-argument constructor, it initializes the properties to default values defined within that constructor. On the other hand, a parameterized constructor allows you to pass specific values during object creation, enabling customizable initialization.
public class Person {
String name;
int age;
// No-argument constructor
public Person() {
name = "Default Name";
age = 0;
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
System.out.println("Person1 - Name: " + person1.name + ", Age: " + person1.age);
Person person2 = new Person("Alice", 30);
System.out.println("Person2 - Name: " + person2.name + ", Age: " + person2.age);
}
}