Search code examples
seleniumupcasting

Why up-casting to Webdriver is done instead of RemoteWebdriver while working with any browser driver in Selenium?


RemoteWebdriver implements Webdriver interface then why don't we up-cast to RemoteWebdriver instead of Webdriver while creating object of any browser driver?


Solution

  • By definition upcasting is

    a variable of Parent class refers to the object of Child class

    In other words if class A is parent, then class B extends A is a child. Upcasting would be:

    B b = new B();
    A a = b; // upcasting
    

    But relationship between RemoteWebDriver and WebDriver is not of a parent/child:

    RemoteWebDriver implements WebDriver
    

    Hence there's no upcasting here. And the question is different:

    why don't we declare concrete type RemoteWebDriver instead of WebDriver while creating object of any browser driver

    the reasons are same as when answering a more generic question: Why should the interface for a Java class be preferred?. And really: if Selenium developers removed/deprecated RemoteWebDriver would you want to change your tests?

    BTW: here's a case of actual upcasting to RemoteWebDriver:

    ChromeDriver driver = new ChromeDriver(); // ChromeDriver extends RemoteWebDriver
    RemoteWebDriver remoteDriver = driver;
    

    Also the following is valid, although hard to find a reason why you'd want to do it:

    WebDriver driver = new ChromeDriver();
    RemoteWebDriver remoteDriver = (RemoteWebDriver) driver;
    

    One use case I've seen is when people want to use some other interface implemented by RemoteWebDriver (i.e. not WebDriver, but say TakesScreenshot). But then it's better to cast to that interface directly:

    WebDriver driver = new ChromeDriver();
    TakesScreenshot ts = (TakesScreenshot) driver;
    ts.getScreenshotAs(...);