Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a base class onto a derived class in Java

Currently in my Java program, I have a base Parent class with several methods which return a new instance of itself. For example:

public BasePage fill(String input, By locator) {
    driver.findElement(locator).clear();
    driver.findElement(locator).sendKeys(input);

    return new BasePage(driver);
}

As well, I have several classes which extend this base class with their own methods. My question is this: is there a way in my main program to call these Parent methods, but assign the returned value to a child class without using casts? For example, if I had a loginPage Child class which needed to use this method in a main program, how would I turn this:

loginPage = (LoginPage) loginPage.fill("username", usernameLocator);

into this:

loginPage = loginPage.fill("username", usernameLocator);

where I initialize the class:

public class LoginPage extends BasePage {
}

While not mentioned in this example, is it possible to allow it to return any of the child classes, such that it is not restricted to just one class.

like image 442
bagelmakers Avatar asked Nov 16 '25 20:11

bagelmakers


1 Answers

Yes, there is a way. In the subclass (e.g. LoginPage), override the fill method. With Java's covariant return types (scroll to the bottom), you can specify LoginPage as the return type.

public LoginPage fill(String input, By locator) {
    driver.findElement(locator).clear();
    driver.findElement(locator).sendKeys(input);

    return new LoginPage(driver);
}

That assumes that you can create a LoginPage with a driver, assumed to be of a Driver class, which means you need a subclass constructor that takes a Driver.

public LoginPage(Driver driver)
{
    super(driver);
    // Anything else LoginPage-specific goes here
}
like image 80
rgettman Avatar answered Nov 19 '25 10:11

rgettman