1

What is the difference between:

ChromeDriver driver = new ChromeDriver ();

and

WebDriver driver = new ChromeDriver ();

Will I get same output if I use any of these codes in Selenium Java?

I didn't any difference in two codes so will my output also same if I use of these two?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Sundar Jakob
  • 37
  • 1
  • 6

2 Answers2

2

ChromeDriver driver = new ChromeDriver();

When using:

ChromeDriver driver = new ChromeDriver();

The ChromeDriver instance will be only able to invoke and act on the methods implemented by ChromeDriver and supported by only. To act with other browsers we have to specifically create individual objects as below :

  • FirefoxDriver driver = new FirefoxDriver();
  • InternetExplorerDriver driver = new InternetExplorerDriver();

WebDriver Interface

From Selenium perspective, the WebDriver Interface is similar like a agreement which the 3rd party Browser Vendors like , , , , etc have to adhere and implement the same. This would in-turn help the end-users to use the exposed APIs to write a common code and implement the functionalities across all the available Browsers without any change.


WebDriver driver = new ChromeDriver();

Using WebDriver driver = new ChromeDriver(); you are creating an instance of the WebDriver interface and casting it to ChromeDriver Class. All the browser drivers like FirefoxDriver, ChromeDriver, InternetExplorerDriver, PhantomJSDriver, SafariDriver etc implemented the WebDriver interface (actually the RemoteWebDriver class implements WebDriver Interface and the Browser Drivers extends RemoteWebDriver). So if we use WebDriver driver, then we can use the already initialized driver (as common object variable) for all browsers we want to automate e.g. Mozilla, Chrome, InternetExplorer, PhantomJS, Safari.

WebDriver driver = new FirefoxDriver();
driver = new ChromeDriver();
driver = new FirefoxDriver();
driver = new SafariDriver();
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

The correct driver initialisation is the second one. Use this:


WebDriver driver = new ChromeDriver ();
Funky Monkey
  • 121
  • 5
  • I am asking difference in outputs. Do you think first code is wrong? – Sundar Jakob Feb 03 '22 at 17:07
  • The first one will work fine, but only for chrome testing. When you use first one, that means you are creating instance of ChromeDriver. As per the java concept if you create an object using New keyword it will initiate constructor of that class. We have object of ChromeDriver class. So to balance that out you should create object of browser driver by referencing it to WebDriver instance like the second option. With the second option you're creating an instance of the WebDriver interface and casting it to browser driver class, which makes more sense:=) – Funky Monkey Feb 04 '22 at 08:29