In our selenium automation scripts, we use
WebDriver driver = new FirefoxDriver();
or
WebDriver driver = new ChromeDriver();
& so on…
But did we ever got a question, why? or why not WebDriver driver = new WebDriver(); ?
Let’s discuss about the why & why not :D
why not WebDriver driver = new WebDriver();?
Answer is – As per the Selenium WebDriver docs, WebDriver is an interface and we can not create instance of an interface.
why not FirefoxDriver driver = new FirefoxDriver();?
This is allowed, but problem is that with this above statement, we can only invoke and automate web application on firefox browser only, for other browsers we have to specifically create individual objects like ChromeDriver driver = new ChromeDriver();
FirefoxDriver driver = new FirefoxDriver();
driver = new ChromeDriver(); //NOT allowed.
Why WebDriver driver = new FirefoxDriver();?
In reality, all the browser drivers like FirefoxDriver, ChromeDriver, IEDriver etc implemented WebDriver interface (infact RemoteWebDriver class implements WebDriver interface and browser drivers extends RemoteWebDriver), so if we will use WebDriver driver, then we can use driver (as common object variable) for all browsers we want to automate.
WebDriver driver = new FirefoxDriver();
driver = new ChromeDriver(); //allowed
driver = new SafariDriver(); //allowed
Hope this helps!