-6
int x=22;
long z=24;
//now in this case int is smaller than long so
z=x; // is quite appropriate as it implicitly converts from int to long(widening)

同样,我们有这样的类:

private static class Box {
    private int width;
    private int height;
    private int length;
    //...
}

private static class WeightBox extends Box {
    private int weight;
    //...
}

public class Main {
    public static void main(String args[]) {
        Box simpleBox = new Box();
        WeightBox wt = new WeightBox();
        simpleBox = wt; //we can always do this
        //wt = simpleBox cannot be done implicitly 
        //for this to work we have to use type casts
    }
}

为什么simpleBox = wtsimpleBox属于基类而wt属于扩展类却能做到?扩展类不应该大于基类吗?

4

2 回答 2

0

因为你声明:

Box simpleBox = new Box();

在这种情况下,“simpleBox”变量被声明为“Box”类型,这意味着您可以将任何与 Box 赋值兼容的对象实例重新分配给它。在声明时,您已经给它一个恰好属于同一类的值。

由于 wt 被声明为“WeightBox”,它是“Box”的子类,因此它是赋值兼容的(上面提到的 liskov 替换原则)。这与这样做没有什么不同:

List<String> list = new ArrayList<String>();
list = new LinkedList<String>();

ArrayList 和 LinkedList 都与 List 兼容。

如果您想在运行时检查它,这是对类本身的简单操作:

Box.class.isAssignableFrom(WeightBox.class)
于 2012-05-31T02:28:45.230 回答
0

考虑铸造时,尺寸无关紧要。查看本教程以了解向上转换和向下转换。方便的是,它是用 Java 编写的。:)

于 2012-05-31T01:13:07.667 回答