Method Overriding in Selenium

Profile picture for user arilio666

Method overriding is the process where in the child class, the method name is the same as that of the method in its base class.

In other words, this can be interpreted as a method allowing a subclass to provide a different implementation of a method already present and defined in its superclass. This mechanism allows the subclass to inherit the properties and behaviors of the superclass while providing its specific implementation.

In Selenium, we can create our webdriver classes.
For example, let us try to extend remoteWebDriver class into our very own class and override the get() method of Selenium.


import org.openqa. Selenium.remote.RemoteWebDriver;
public class Over extends RemoteWebDriver {
    @Override
    public void get(String url) {
        System.out.println("Navigating to URL: " + url);
        super.get(url);
    }
}
  • We can see here that we have extended the RemoteWebDriver and created a get method with an argument.
  • We can see the @override. This indicates that this method will override the superclass's existing get() method.
    Let us check it out.
public class DropDown extends Over {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DropDown d = new DropDown();
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        // driver.get("http://autopract.com/selenium/dropdown1/");
        d.get("http://autopract.com/selenium/dropdown1/");
        driver.manage().window().maximize();
        WebElement dropD = driver.findElement(By.xpath("//select[@class='custom-select']"));
        Select e1 = new Select(dropD);
        e1.selectByVisibleText("Football");
        e1.selectByIndex(3);
        }}
     
  •    Here we can see that we extended the over class and then created object for the DropDown to access the overridden method in the over class.
  • We can see clearly that our custom method works, and the get() method has been overridden.