Method Overloading in Selenium

Profile picture for user arilio666

In this article, we will see how we can overload methods on selenium java. Method overloading uses two same method names but with different parameters.

It allows us to define multiple methods with the same name but different arguments, types of arguments, or both in a single class. In Selenium, method overloading can be used to perform the same actions.

In this article, for example, we will be using the dropdown as an example of method overloading.

Autopract dropdown site will be used.

1.) Overloading

Let us create a class with a bunch of dropdown methods from the select class from Selenium.

package week4.day2;
import org.openqa. Selenium.support.ui.Select;
public class List {
    static Select list;
    public List(Select list) {
        this.list = list;
    }
    public void select(int i) {
        this.list.selectByIndex(i);
    }
    public void select(String text) {
        this.list.selectByVisibleText(text);
    }
    public void deSelect(int i) {
        this.list.deselectByIndex(i);
    }
    public void deSelect(String text) {
        this.list.deselectByVisibleText(text);
    }
}
  • Here we have created a class called List and made some methods with the same name, which is overloading.
  • But if you watch closely, the parameters are different, although the methods are the same.
  • One is by an integer, and another by a string.
  • This is the thing that separates from the same method name.

2.) Operation

Let us create another class, extend this, and use some of the methods from List.

package week4.day2;
import org.openqa. Selenium.By;
import org.openqa. Selenium.WebElement;
import org.openqa. Selenium.chrome.ChromeDriver;
import org.openqa. Selenium.support.ui.Select;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DropDown extends List {
    public DropDown(Select list) {
        super(list);
        // TODO Auto-generated constructor stub
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://autopract.com/selenium/dropdown1/");
        driver.manage().window().maximize();
        DropDown d = new DropDown(list);
        WebElement dropD = driver.findElement(By.xpath("//select[@class='custom-select']"));
        list = new Select(dropD);
        d.select("Football");
        d.select(0);
    }
}
  • We can see the constructor for the class List has been created after extending.
  • After creating an object for the current class, we can access the List class methods.
  • We created the list by passing the select xpath into the static list variable. We can now target the select box on the webpage.
  • So this is how method overloading is done in java selenium.