A constructor initializes an object when it is created. It runs automatically when you call new. In automation, constructors set up WebDriver instances, initialize page elements, and configure test data.
public class Browser {
String name;
String version;
boolean isHeadless;
// Constructor
Browser(String name, String version) {
this.name = name;
this.version = version;
this.isHeadless = false;
}
// Overloaded constructor
Browser(String name, String version, boolean isHeadless) {
this.name = name;
this.version = version;
this.isHeadless = isHeadless;
}
void launch() {
String mode = isHeadless ? "headless" : "headed";
System.out.println("Launching " + name + " v" + version + " (" + mode + ")");
}
}public class BrowserTest {
public static void main(String[] args) {
Browser chrome = new Browser("Chrome", "120");
Browser firefoxHeadless = new Browser("Firefox", "119", true);
chrome.launch(); // Launching Chrome v120 (headed)
firefoxHeadless.launch(); // Launching Firefox v119 (headless)
}
}new is usedpublic class TestConfig {
String browser;
String env;
int timeout;
TestConfig() {
this("chrome", "qa", 30);
}
TestConfig(String browser) {
this(browser, "qa", 30);
}
TestConfig(String browser, String env, int timeout) {
this.browser = browser;
this.env = env;
this.timeout = timeout;
}
void print() {
System.out.println(browser + " | " + env + " | timeout: " + timeout + "s");
}
public static void main(String[] args) {
new TestConfig().print(); // chrome | qa | timeout: 30s
new TestConfig("firefox").print(); // firefox | qa | timeout: 30s
new TestConfig("edge", "prod", 60).print(); // edge | prod | timeout: 60s
}
}Q: What is the difference between a constructor and a method?
A: A constructor has the same name as the class and no return type — it initializes an object when created with new. A method has its own name and a return type (including void) — it performs an action on an existing object. Constructors run once at object creation; methods can be called repeatedly.
Exercise 1: Create a LoginPage class with fields: driver (String for now), url, and timeout. Write two constructors — one that takes all 3 parameters, and one that takes only driver and uses default values for url and timeout.
Exercise 2: What happens if you create a class with a parameterized constructor and try to create an object with no arguments? Try it and observe the error.