Friday, January 18, 2019

Why we need to down cast WebDriver reference for JavaScriptExecutor and TakesScreenshot in Selenium?

Let us understand this with below java program example.

I have class A and interface B as shown below, class A is having a method call sayBye(), interface B is having a declared method sayHello().

Now let class A implement interface B, and implement the sayHello() method of interface B in class A as shown below.



Now create object to class A and try to access the both methods in method.


I am able to access both the methods of class A and interface B.

Now create object to class A of reference type interface B, and try accessing both the methods. I will get an error while accessing the sayBye() method as shown in the below screenshot. 


The reason is sayBye() method belongs to class A, which is not visible to interface B type reference, so we can't access.

Lets create one more interface C which has declared method sayGoodMorning(). Our class A implements the interfaces B and C as shown in the below screenshot.


If we observe the above screenshot, in the main() method we created object to class A of type A and we are able to access all the methods, i.e class A method, interface B method and interface C method.

Now create object to class A of type interface B (or C), and try accessing the all the methods again.


We can see error when we are trying to access sayBye() & sayGoodMorning(), because the object type is of interface B, which can access only interface B methods implemented in class A, it can access neither class A or interface C methods.

Similarly RemoteWebDriver() is class in Selenium architecture that implements interfaces like WebDriver(), JavaScriptExecutor(), TakesScreenshot() and etc. The RemoteWebDriver class will look something like as shown in the below screenshot.


So when we write WebDriver driver = new FirfoxDriver() we are creating a object to class FirefoxDriver() of type WebDriver (here FirefoxDriver() extends RemoteWebDriver() class intrenally), so driver object can not see the implemented methods of JavaScriptExecutor() and TakesScreenshot().

To access the methods of interfaces JavaScriptExecutor() and TakesScreenshot() which are implemented in RemoteWebDriver class, we should be down cast the driver object to respective reference type.

Thanks for reading. #HappyTesting #HappyLearning

No comments:

Post a Comment

Selenium4: Working with two parallel windows in Selenium Automation

A new method newWindow() is introduced in Selenium 4 (Alpha). Using this method we can open a new tab or new window from the current window...