Answer
Constructors in Java
A constructor is a special method that is automatically called when an object is created using new. It has the same name as the class and no return type.
Types of Constructors
1. Default Constructor (No-arg)
Provided by Java automatically if you don''t define any constructor. Sets all fields to default values.
public class Car {
String brand;
int speed;
// Default constructor (Java creates this automatically if not defined)
public Car() {
brand = "Unknown";
speed = 0;
}
}
Car car = new Car(); // calls default constructor
System.out.println(car.brand); // "Unknown"
2. Parameterized Constructor
Accepts arguments to initialize fields with specific values.
public class Car {
String brand;
int speed;
String color;
public Car(String brand, int speed, String color) {
this.brand = brand; // 'this' refers to current object
this.speed = speed;
this.color = color;
}
}
Car car1 = new Car("Toyota", 120, "Red");
Car car2 = new Car("BMW", 200, "Black");
3. Copy Constructor
Creates a new object as a copy of an existing object.
public class Car {
String brand;
int speed;
public Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
// Copy constructor
public Car(Car other) {
this.brand = other.brand;
this.speed = other.speed;
}
}
Car original = new Car("Honda", 100);
Car copy = new Car(original); // copy constructor
copy.brand = "Modified";
System.out.println(original.brand); // "Honda" — not affected
Constructor Overloading
Multiple constructors with different parameter lists.
public class User {
String name;
String email;
String role;
public User() {
this("Unknown", "N/A", "viewer"); // calls 3-arg constructor
}
public User(String name) {
this(name, "N/A", "viewer");
}
public User(String name, String email, String role) {
this.name = name;
this.email = email;
this.role = role;
}
}
Constructor vs Method
| Aspect | Constructor | Method |
|---|---|---|
| Name | Same as class | Any name |
| Return type | None (not even void) | Must have return type |
| Called | Automatically on new | Manually |
| Purpose | Initialize object | Perform operation |
In Automation Frameworks
public class BasePage {
protected WebDriver driver;
protected WebDriverWait wait;
// Constructor — called when BasePage (or subclass) is created
public BasePage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
PageFactory.initElements(driver, this);
}
}
// LoginPage inherits and calls parent constructor
public class LoginPage extends BasePage {
public LoginPage(WebDriver driver) {
super(driver); // calls BasePage constructor
}
}
