In this tutorial, we'll delve into constructors, which are fundamental for initializing objects in Java. By the end of this session, you'll have a solid understanding of what constructors are and how to use them effectively.
What is a Constructor?
class Car {
String make;
String model;
// Constructor
Car(String make, String model) {
this.make = make;
this.model = model;
}
}
Car myCar = new Car("Toyota", "Camry");
class Car {
String make;
String model;
}
Car myCar = new Car(); // Default constructor is called
class Car {
String make;
String model;
// Parameterized Constructor
Car(String make, String model) {
this.make = make;
this.model = model;
}
}
Car myCar = new Car("Toyota", "Camry");
class Car {
String make;
String model;
// Constructor 1
Car(String make, String model) {
this.make = make;
this.model = model;
}
// Constructor 2
Car(String make) {
this.make = make;
this.model = "Unknown";
}
}
Car car1 = new Car("Toyota", "Camry");
Car car2 = new Car("Honda");
class Car {
String make;
String model;
// Constructor 1
Car(String make, String model) {
this.make = make;
this.model = model;
}
// Constructor 2 (calls Constructor 1)
Car(String make) {
this(make, "Unknown");
}
}
Car car = new Car("Honda");