Search code examples
javaseleniumooppolymorphism

Is there a way to pass different (but specific) types of objects in same method and have different ways to handle based on the type of object


I have to write a method that will click on an element present on the web page. The problem is I can have only either of the two types of objects in my method i.e. either a 'WebElement' object or a 'By' object. So, in order to do that I have to write repetitive lines of code for the two overloaded methods as shown below:

    public void clickElement(WebElement element) {
        Line 1;
        Line 2;
        element.click();
        Line 3;
    }
    
    public void clickElement(By locator) {
        Line 1;
        Line 2;
        driver.findElement(locator).click();
        Line 3;
    }

Is it possible to write only one method which is can take only one of either two types of object and behave accordingly? Something like this:

public void clickElement(WebElement element **OR** By locator) {
        Line 1;
        Line 2;
        element.click; **OR** driver.findElement(locator).click();
        Line 3;
    }

Let me know if my question needs more clarification or inputs.

Solution

  • I did not use selenium. Based on your code, I am assuming driver.findElement() returns WebElement, and Line 1, 2, 3 is exactly the same in both methods. If this is the case, the best way I can think of to implement this is as follows.

        public void clickElement(WebElement element) {
            Line 1;
            Line 2;
            element.click();
            Line 3;
        }
        
        public void clickElement(By locator) {
            clickElement(driver.findElement(locator));
        }
    

    By doing so, we can maximize code reuse while preserving the method signature which enforces the type of class that can be passed to these methods.