基类和派生类之间的大小差异

时间:2012-05-31 00:59:34

标签: java

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 = wt可以完成,即使simpleBox属于基类而wt属于扩展类;扩展类不应该大于基类吗?

2 个答案:

答案 0 :(得分:0)

考虑铸造时尺寸无关紧要。查看此tutorial有关向上转发和向下转发的信息。方便的是,它是用Java编写的。 :)

答案 1 :(得分: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)