#hyperskill类型擦除(java)违反者问题,为什么我的解决方案不起作用?

c86crjj0  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(289)

问题链接
问题陈述:
您被要求在烘焙公司执行安全审计。他们的产品以烘焙类及其不同的子类(如蛋糕和柠檬)为代表。所有的糕点都装在漂亮的盒子里卖。在发布给客户之前,所有的框都经过仔细设计的naivequalitycontrol类的检查。然而,最近发生了一些错误,无法食用的东西被 Package 在盒子里,并逃脱了质量检查。
简单地看一下naivequalitycontrol,您就会得出这样的结论:在naivequalitycontrol中,装满纸张的盒子很容易通过qc。现在你的任务是证明这个错误。代码如下:

/* This class and its subclasses should pass quality check */
class Bakery {}

class Cake extends Bakery {}

/* This one should not */
class Paper {}

/* These boxes are used to pack stuff */
class Box<T> {
    void put(T item) { /* implementation omitted */ }
    T get() { /* implementation omitted */ }
}

/* This quality checker ensures that boxes for sale contain Bakery and anything else */
class NaiveQualityControl {

  public static boolean check(List<Box<? extends Bakery>> boxes) {
    /* Method signature guarantees that all illegal 
       calls will produce compile-time error... or not? */  
    return true;  
  }

}

您需要将实现添加到violator.defraud()方法,该方法将执行以下操作:
创建方框列表<?根据方法签名扩展bakery>
将纸张对象至少放在列表中的一个框中
结果列表应通过naivequalitycontrol检查
我的解决方案:

import java.util.ArrayList;
class Violator {

    public static List<Box<? extends Bakery>> defraud() {
        Paper paper = new Paper();
        Box paperBox = new Box();
        paperBox.put(paper);
        List<Box<? extends Bakery>> boxes = new ArrayList<>();
        boxes.add(paperBox);
        return boxes;
    }
}

我的解决方案是工作,但我想出了它使用击中和审判方法,所以我不知道为什么这是工作。纸张类即使没有扩展烘焙类,仍然设法添加到框列表中?
还有一个疑问,为什么这个解决方案不起作用?

import java.util.ArrayList;
class Violator {

    public static List<Box<? extends Bakery>> defraud() {
        Paper paper = new Paper();
        Box<? extends Object> paperBox = new Box<>();// It should accept any type of box as any reference type is subclass of Object class...right?
        paperBox.put(paper);
        List<Box<? extends Bakery>> boxes = new ArrayList<>();
        boxes.add(paperBox);
        return boxes;
    }
}

错误:

Compilation error
Main.java:7: error: incompatible types: Paper cannot be converted to CAP#1
        paperBox.put(paper);
                     ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ? extends Object
Main.java:9: error: incompatible types: Box<CAP#1> cannot be converted to Box<? extends Bakery>
        boxes.add(paperBox);
                  ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ? extends Object
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题