title: Casting a base class onto a derived class in Java
body: <p>Currently in my Java program, I have a base Parent class with several methods which return a new instance of itself. For example:</p>
  
  <pre><code>public BasePage fill(String input, By locator) {
      driver.findElement(locator).clear();
      driver.findElement(locator).sendKeys(input);
  
      return new BasePage(driver);
  }
  </code></pre>
  
  <p>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 <code>loginPage</code> Child class which needed to use this method in a main program, how would I turn this:</p>
  
  <pre><code>loginPage = (LoginPage) loginPage.fill("username", usernameLocator);
  </code></pre>
  
  <p>into this:</p>
  
  <pre><code>loginPage = loginPage.fill("username", usernameLocator);
  </code></pre>
  
  <p>where I initialize the class:</p>
  
  <pre><code>public class LoginPage extends BasePage {
  }
  </code></pre>
  
  <p>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.</p>