Method Overloading Vs Method Overriding - automation testing
Introduction
Overriding and overloading are the core concepts in Java programming. They are the ways to implement polymorphism in our Java programs.
1. Overloading in Java
Overloading Example in Selenium
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class SeleniumOverloadingExample {
WebDriver driver;
// Constructor
public SeleniumOverloadingExample(WebDriver driver) {
this.driver = driver;
}
// Click method with locator as By
public void clickElement(By locator) {
driver.findElement(locator).click();
}
// Overloaded Click method with WebElement
public void clickElement(WebElement element) {
element.click();
}
// Overloaded Click method with String (XPath as String)
public void clickElement(String xpath) {
driver.findElement(By.xpath(xpath)).click();
}
public static void main(String[] args) {
WebDriver driver = // initialize WebDriver (e.g., new ChromeDriver());
SeleniumOverloadingExample example = new SeleniumOverloadingExample(driver);
// Example calls
example.clickElement(By.id("submitBtn")); // By locator
WebElement element = driver.findElement(By.name("q")); // WebElement
example.clickElement(element); // WebElement
example.clickElement("//button[@type='submit']"); // XPath as String
}
}
2. Overriding in Java
Overriding Example in Selenium
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
class CustomChromeDriver extends ChromeDriver {
@Override
public void get(String url) {
System.out.println("Opening URL in Chrome: " + url);
super.get(url); // Call parent class's method
}
}
class CustomFirefoxDriver extends FirefoxDriver {
@Override
public void get(String url) {
System.out.println("Opening URL in Firefox: " + url);
super.get(url); // Call parent class's method
}
}
public class SeleniumOverridingExample {
public static void main(String[] args) {
WebDriver driver;
// Use Custom ChromeDriver
driver = new CustomChromeDriver();
driver.get("https://example.com");
// Use Custom FirefoxDriver
driver = new CustomFirefoxDriver();
driver.get("https://example.com");
}
}