0

When I use PageFactory.initElements in parent class, child class elements are initialized. How this is working?

public class PageBase {

    public PageBase(WebDriver dr)
    {
        this.dr=dr;
        PageFactory.initElements(dr, this);
    }
}

Here in PageBase(parent), 'this' is reference of PageBase(parent) right? then how its initializing elements in below child class? is this because of inheritance[i.e something like child class also will be initialized with parent]?

public class LoginPage extends PageBase{
    private WebDriver dr;
    public LoginPage(WebDriver dr)
    {
        super(dr);
        this.dr=dr;
        //PageFactory.initElements(dr, this);
    }
    @FindBy(how=How.ID,using="Bugzilla_login")
    WebElement weUserName;
    @FindBy(id="Bugzilla_password")
    WebElement wepassword;
    @FindBy(how=How.XPATH,using="//input[@id='log_in']")
    WebElement weLoginBtn;
} 
AtomNew
  • 59
  • 8

1 Answers1

0

this is a reference to the PageBase child instance being created; this always refers to the concrete runtime class.

We can prove it with a simple example.

public class Main {
    public static void main(String... args) {
        Parent aParent = new Child("foo");
    }

    static class Parent {
        Parent(String someArg) {
            Factory.initElements(someArg, this);
        }
    }

    static class Factory {
        static void initElements(String someArg, Parent p) {
            System.out.println( "Parent object 'p' is an instance of class: " + p.getClass().getSimpleName() );
        }
    }

    static class Child extends Parent {
        Child(String someArg) {
            super(someArg);
        }
    }
}

Parent object 'p' is an instance of class: Child

Note that depending on your IDE settings, you may see a Leaking this in constructor warning.

jaco0646
  • 15,303
  • 7
  • 59
  • 83