Do's and Dont's of Interfaces in Java. Is it allowed to do WebDriver driver = new WebDriver() in Selenium ?


You would have often seen this line of code in Selenium,

WebDriver driver = new FireFoxDriver;

WebDriver is an Interface,and we are defining a reference variable(driver) to this interface.

Any object that we create refering to this interface Webdriver has to be an instance of a class only i.e FireFoxDriver. This Class FireFoxDriver implements the interface WebDriver.





Do's : Important Points to Note

If we want to instantiate an instance i.e create and Object of an instance, we must do so only after we have created a Class that implements the interface.

Class implementing the interface must implement all the methods declared in the interface.Now our FirefoxDriver class should implement all the methods declared inside an WebDriver interface, same is the case with ChromeDriver or IEDriver classes.

We must respect the signature of the method declared in the interface and follow exactly same signature(i.e Name and Parameters of method) while implementing in the Class.

All of the variables declared inside an interface are Final by default .

An Interface can Extend another Interface but then the class which implements the interface need to implemented the methods of both interface .

A Class can implement multiple Interface

Nested Interfaces are allowed i.e An interface can have another interface.



Dont's : Important Points to Note


Class cannot Extend Interface only Implements it.

We can not instantiate/create object of an Interface. webdriver driver = new webdriver ();

Class cannot extend multiple classes,multiple inheritance in class is not possible

Interface can not hold constructor.

Interface can not hold instance fields/variables.

By default all the methods of Interface are public so no need to provide access modifiers.


Verdict: We can not instantiate i.e. create an object of an Interface, therfore WebDriver driver = new WebDriver() is incorrcet statement and is not allowed.