简体   繁体   中英

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

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM