0

I am passing a WebDriver instance to the class below as

FunctionalComponents fc = new FunctionalComponents(driver)

from another class, but the object creation happens before constructor is executed. As it is, the objects created are having null value in the driver instance.

How can I solve this problem?

public class FunctionalComponents  
{    
    public FunctionalComponents(WebDriver driver) 
    {
        this.driver = driver;                            
    }

    CaptureElement element= new CaptureElement(driver);

    public void Method()
    {
        // method logic
        // i call object element here
    }
}

1 Answer 1

2

Don’t set the value of your member variable outside during the field definition. Do it from within the constructor, which will guarantee the population of the variables as you’d like. To wit:

public class FunctionalComponents  
{
    private IWebDriver driver;
    private CaptureElement element;

    public FunctionalComponents(WebDriver driver) 
    {
        this.driver = driver;
        this.element = new CaptureElement(driver);
    }

    public void Method()
    {
        // method logic
        // i call object element here
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Jim, you haven't declared the driver instance in the FunctionalComponents class. I think you meant to add private WebDriver driver;? Otherwise this.driver is going to fail... well it won't compile but you know what I mean.
Neither will the original poster’s code, for the same reason. :) Of course, you’re right, but I was really just trying to demonstrate the solution. Edited answer to fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.