why we assign firefoxdriver instance to webdriver

前端 未结 8 1621
时光说笑
时光说笑 2021-02-06 16:52

I am novice to Java or Selenium.

I just need help to understand one basic question.

Why we assign firefoxdriver instance to WebDriver? WebDriver driver=new Firef

相关标签:
8条回答
  • 2021-02-06 17:30

    I know that this is kind of Late binding in Java,

    No. This is an example of compile time binding. But yes, it's also an example of programming to the WebDriver interface.

    Question1: But this applies [sic] to classes, right?

    It could (conceivably) be an interface that extends WebDriver.

    Question2: WebDriver is an interface, then can we create an object instance of an interface?

    Yes, you can create concrete instances that implement an interface. In fact, to use any interface there must be at least one concrete implementation.

    0 讨论(0)
  • 2021-02-06 17:32
    WebDriver driver = new FirefoxDriver();
    

    In the above statement, WebDriver is an interface. An interface contains empty methods that have been defined but not implemented. These methods can be implemented by anyone as long as the method type and signatures are not violated. Therefore, an interface is also known as contract, because you can use an interface as you like but you cannot change the way it has been defined. And, since it has empty methods you won't actually need to instantiate it and so you cannot instantiate it.

    FirefoxDriver is a class that has been written specifically for the Firefox browser. It has methods that are implemented and it can be instantiated. It can perform all functions (or methods) on the Firefox browser as defined in the interface WebDriver.

    So in the above statement, we are actually telling FirefoxDriver class that "hey you can automate the various methods that you want on the Firefox browser but you need to stick to the contract defined in WebDriver". So we declare a reference variable of type WebDriver and then use it to instantiate FirefoxDriver, which means that the object (driver) is of type WebDriver but points to the memory allocation to all data and methods in FirefoxDriver (and, as mentioned above, the FirefoxDriver class already has the implemented version of methods in WebDriver). So all good :)

    By using this technique, we have made it easy for the tester to use any browser of his or her liking. For example, to automate on IE driver, one will have to simply write a statement like

    WebDriver driver = new IEDriver(); //where IEDriver is the class written for IE
    
    0 讨论(0)
提交回复
热议问题