Is it possible to specify both upper and lower bound constraints on type parameters in Java?

后端 未结 3 615
南旧
南旧 2020-12-09 10:12

Is it possible to specify both upper and lower bound constraints on type parameters in Java?

I found a conversation in Sun\'s forum in which this issue was discussed

3条回答
  •  暖寄归人
    2020-12-09 10:47

    you can't specify both at the same time but you can achieve like given code.

    class Family {
        F f;
    
        public void setF(F f) {
            this.f = f;
        }
    }
    
    class GrandParent {
    }
    
    class Parent extends GrandParent {
    }
    
    class Child extends Parent {
    }
    
    private  void foo(Family list) {
        list = new Family(); // Allows
        list = new Family(); // Allows
        list = new Family(); // Not Allows
    
        list.setF(new GrandParent()); // Not Allows
        list.setF(new Parent()); // Not Allows
        list.setF(new Child()); // Not Allows
    }
    
    public void bar() {
        foo(new Family()); // Allows
        foo(new Family()); // Allows
        foo(new Family()); // Allows
    }
    

提交回复
热议问题