pradeep
pradeep

Reputation: 35

How to use variables initialized in one method into another method in another class

I am new to java and hence I need to know that how can I use a variable which I have initialised in one method, into another method. So I have a variable driver which is initialised in method a and I want to use it in method b, how can I do it or can I do it in the first place?

class Selenium{

 WebDriver driver;

   public void a(){
       driver = new FirefoxDriver();

     }

   public void b(){
       driver.get(url);
       driver.findElement(By.xpath(xpath)).click();
     }
}

Upvotes: 0

Views: 61

Answers (1)

Naman
Naman

Reputation: 32036

In your current context, all you need to do is make sure the method a is being called in the method b before making use of the driver object.

public void b(){
    a(); // makes sure the 'driver' in the class is not null for the next statement
    driver.get(url);
    driver.findElement(By.xpath(xpath)).click();
}

In case there are fields which are local to a method and you need to provide its value to another method, you shall make use of arguments.

Upvotes: 1

Related Questions