Skip to content
Advertisement

Can someone explain how WebDriver casting to TakesScreenShot in Selenium working

This is a JAVA conceptual question, not related to Selenium.

For a sample code like :

// Taking a screenshot in Selenium
WebDriver driver= new ChromeDriver();
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

When I observe, WebDriver and TakesScreenshot do not share a common super interface. In that case how can casting be valid and why not a ClassCastException?

It would be really great if this can be explained with an example.

Advertisement

Answer

Let’s take Selenium out of the picture and use built-in types for simplicity. Your code is similar (in terms of casting) to this:

Comparable<String> text = "hello";
int length = ((CharSequence) text).length();

This compiles and executes without an exception because:

  • "hello" is a String
  • String implements both Comparable<String> and CharSequence
  • The cast to CharSequence is concerned by the execution-time type of the object that the value of text refers to, not the compile-time type text

At execution time, the value of text refers to a String object (“hello”). The fact that the compile-time type is Comparable<String> is irrelevant when it comes to the cast – so long as it’s possible. (If you try to cast an expression with a compile-time type which can’t possibly be valid, e.g. casting from String to InputStream, then you’ll get a compile-time error. But when the compiler is happy that the cast could potentially succeed, the compile-time type of the variable is irrelevant when it comes to the execution-time handling of the cast.)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement