0

I'm trying to better understand generics in Java, and confronted with some issue. Please, help to find out why in following code class "BPage" using data from "APageData" instead of "BPageData"?

public abstract class PageData {}

public abstract class Page<T extends PageData> {
    public T pageData;
    public Page(T pageData) {
        this.pageData = pageData;
    }
}



public class APageData extends PageData {
    public final String locator = "//*[@id=\"id_1\"]";
}
public class APage<T extends APageData> extends Page<APageData> {
    public APage(T pageData) {
        super(pageData);
    }

    public void getLocator() {
        System.out.println(pageData.locator);
    }
}



public class BPageData extends APageData {
    public final String locator = "//*[@class=\"class_1\"]";
}
public class BPage extends APage<BPageData> {
    public BPage(BPageData pageData) {
        super(pageData);
    }
}


 public class Main {
    public static void main(String[] args) {
        APage aPage = new APage(new APageData());
        aPage.getLocator(); 

        BPage bPage = new BPage(new BPageData());
        bPage.getLocator();
    }
}

the result is

//*[@id="id_1"]

//*[@id="id_1"]

  • Your `APage` definition isn't correct. I think you meant `extends Page` not `extends Page`. More generally: I don't think generics are helping you here at all. Simple subtype polymorphism would give you the effect you want and would be a lot easier to reason about in this case. – Daniel Pryden Mar 01 '18 at 20:00
  • Your specific problem here is actually because `BPageData.locator` shadows (but does not replace) `APageData.locator` in the parent class. So if you access `pageData.locator` where `pageData` has a static type of `APageData` (which it does here), then you will get the `locator` field declared on `APageData`, not the one declared on `BPageData`. If you used an accessor method (getter) then you wouldn't have this problem, because the getter would be dispatched polymorphically. – Daniel Pryden Mar 01 '18 at 20:08

0 Answers0