RArora
RArora

Reputation: 234

Why Cannot call child class method from object of interface implemented in parent class

public interface WebDriver {
    default void get() {
        System.out.println("Opening Url");}

    void click();
    void sendKeys();
}

public class RemoteWebDriver implements WebDriver {
    @Override
    public void click() {
        System.out.println("Clicking WebElement");
    }

    @Override
    public void sendKeys() {
        System.out.println("Entering Text");
    }
}

public class ChromeDriver extends RemoteWebDriver {
    public void clear() {
        System.out.println("Clearing Text");
    }
}

public class TestClass {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get();
        driver.click();
        driver.sendKeys();
        driver.clear();
    }
}

driver.clear(); in TestClass gives error. "The method clear() is undefined for the type WebDriver"

2 quick fixes available:

I know this

((ChromeDriver) driver).clear(); 

fixes the problem. But could anyone explain more logically, why it is not allowing to call child class methods

Upvotes: 1

Views: 391

Answers (1)

trinath
trinath

Reputation: 521

Because at compile time it will check method in parent class or interface, so it will give compilation error if method not found in parent interface

Upvotes: 1

Related Questions