Question

I am newbie to Selenium.

I am writing piece of code DriverManager.Java (to Load Browser)

package com.moni.tef;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DriverManager {

    private static WebDriver driver;

    static {
        driver = new FirefoxDriver();
    }
    public WebDriver getWebDriver(){
        driver.get("https://public-testing/");
        return driver;
    }
}

and I created another class.. and tries to use this getWebDriver method.. Then my piece of code changes in to public static. Code is running but can any one explain what is this fix (done by eclipse)

public static WebDriver getWebDriver(){
    driver.get("https://xxx.url.url");
    return driver;
}
Was it helpful?

Solution

IMO, in your newly written class, you tried to call the getWebDriver() method statically:

DriverManager.getWebDriver()

instead of creating an instance of DriverManager firstly:

new DriverManager().getWebDriver()

This would cause a compilation error since initially, DriverManager#getWebDriver() is an instance method, not a class method (thereby static).

Therefore, Eclipse probably helped you (with your involontary approbation surely) by making the method static in order to compile successfully.

For more information about static concept: click here.

OTHER TIPS

Static members are common for all instances of a class. Non static members are specific to an instance of a class (object). Static methods and members (fields, properties) are used in cases where they don't need to change for the duration of a program's or API's life time. An example of this is Math.PI. A more common (correct) way of describing them is: Static methods and fields are useful when they conceptually don't belong to an instance of something.

Static members also have the property of being accessible from anywhere (unless declared without public) without having an instance (object) of a class.

The special static {} block of a class is run only once when the class is loaded by the JVM.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top