We can utilize methods from classes in Java in multiple ways. One common approach is through inheritance, where a subclass extends a parent class or implements an interface to access its methods. Another approach is by creating an instance of the class and directly invoking its methods.
When we initialize a class without parameters, the default (empty) constructor is automatically called. However, if we want to pass parameters during initialization, we must explicitly create a constructor in the class that accepts those parameters.
Using constructors is especially helpful for initializing variables that can later be used across different methods of the class. This becomes particularly useful in software development and automation testing frameworks, where object initialization and data handling play a key role.
Below is an example script demonstrating how to call a constructor in Java:
Example Code:
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
// Constructor with parameter
public LoginPage(WebDriver driver) {
this.driver = driver; // 'this' refers to the class variable
}
// Method using the initialized driver
public void navigate() {
driver.get("https://www.google.com");
}
}
Usage Example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestLogin {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
// Passing driver instance to constructor
LoginPage loginPage = new LoginPage(driver);
// Using class method
loginPage.navigate();
driver.quit();
}
}