-3

While writing selenium code I had seen a statement:-

public static WebDriver driver = new Firefox Driver();

Now I have multiple questions:-

  1. WebDriver is an interface. Can an interface be static? If yes as per my understanding all the methods part of this interface will also be static methods.
  2. As per my understanding for static class/method/variable no object should be defined as static cannot be instantiated. But from the above program statement it appears we are creating a new object of the WebDriver class although it is static. Please clarify how is this possible or is there a deviation in my understanding?

2 Answers2

1
  • For #2:

    public static WebDriver driver = new Firefox Driver();
    

Above statement is not creating an object of Webdriver interface but it creates an object of class FirefoxDriver. FirefoxDriver is a class that inherits or implements interface WebDriver.

Rakesh Raut
  • 183
  • 3
  • 12
0

First of all your understanding of what is static is incorrect. In public static WebDriver driver = new FirefoxDriver();, WebDriver is type of the object, while driver is an instance of the object. When you declare a member as static, it refers to its instance, not its type. So you are not "making" WebDriver static, you are making driver static.

So the question "Can an interface be static?" does not apply to your situation at all. But if you care about it anyways, the answer is yes, you can define interface like this and it will be static for the parent class:

 public class WithStaticInterface 
 {
     public static interface MyInterface
     {
         void hello();
     }
 }

However the members of the interface can never be static

I suggest reading more on what static members mean. For example here:

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Community
  • 1
  • 1
timbre timbre
  • 12,648
  • 10
  • 46
  • 77