Java - Defining a member that extends class A and implements interface B

前端 未结 2 841
悲哀的现实
悲哀的现实 2020-12-21 17:30

I have a variable that must meet two conditions, and I want to set them in the definition

I know that I can define either condition with an individual variable, like

2条回答
  •  半阙折子戏
    2020-12-21 17:53

    While Java does not directly support intersection types like A&B, such types do appear in type parameter bounds and capture conversions. We can express A&B with a layer of abstraction.

    public class ValueAB
    {
        public final T v;
    
        // constructor ...
    }
    
    public class ClassAB
    {
        public final Class clazz;
    
        // constructor ...
    }
    

    Instead of A&B, Class, we use wrappers ValueAB, ClassAB

        ClassAB clazz = new ClassAB<>(Foo.class);   
    
        ValueAB value = new ValueAB<>(clazz.c.newInstance());
    
        value.v.methodOfA();
        value.v.methodOfB();
    

    This solution would require a wrapper for each combination of As and Bs.


    Another solution is to use only A as type parameter bound; B will be supplied by wildcard bound. This is probably better if you need to express multiple A&B1, A&B2, ... types at use site.

    public class ValueA
    {
        public final T v;
        ...
    }
    
    
    public class ClassA
    {
        public final Class c;
        ...
    }
    
    ---
    
        ClassA clazz = new ClassA<>(Foo.class);
    
        ValueA value = new ValueA<>(clazz.c.newInstance());
    

    If it's confusing how wildcard works in these cases, see my article on wildcard


    A 3rd solution is free of A or B at declaration site of wrappers; the use site provides A and B.

    public class Value
    {
        public final T v;
        ...
    }
    
    
    public class Clazz
    {
        public final Class c;
        ...
    }
    
    ---
    
        Clazz clazz = new Clazz<>(Foo.class);
    
        Value value = new Value<>(clazz.c.newInstance());
    

    This is however probably too confusing.

提交回复
热议问题