How to access different attributes of different implementation of the same interface

144 views Asked by At

I have an interface

public interface Inter {
    int interAttr = 0;   
}

And two classes that implements it, each one with an additional attribute and each one of different type.

@AllArgsConstructor
public class Impl1 implements Inter {
    public int impl1Attr;
}

@AllArgsConstructor
public class Impl2 implements Inter {
    public String impl2Attr;
}

And I have list of Inter objects that are a mix of Impl1 and Impl2

public class main {
    public static void main(String[] args) {
        Impl1 i11 = new Impl1(0);
        Impl1 i12 = new Impl1(1);
        Impl2 i21 = new Impl2("zero");
        Impl2 i22 = new Impl2("one");
        List<inter> implList = new ArrayList<Inter>();
        implList.add(i11);
        implList.add(i12);
        implList.add(i21);
        implList.add(i22);
        for (Inter el : implList){
            // this of course works
            int a = el.interAttr1;
            // But how do I get access to impl1Attr and impl2Attr?
        }
    }
}

Of course I can query i11.impl1Attr or impl21.impl2Attr in the body of the main But is there a way for me to have access to the attributes of the different implementations in the list in the for loop?

1

There are 1 answers

2
Thomas Portwood On BEST ANSWER

I'm probably oversimplifying the problem, but is instanceof + casting not an option?

for (Inter el : implList) {

    int a = el.interAttr;

    if (el instanceof Impl1)
        System.out.println(((Impl1)el).impl1Attr);

    if (el instanceof Impl2)
        System.out.println(((Impl2)el).impl2Attr);
}