[Solved] Size difference between base class and derived class


Because you declared:

Box simpleBox = new Box();

In this case, the “simpleBox” variable is declared of type “Box” this means that you can re-assign any object instance to it that is assignment compatible with Box. At declaration time, you’ve given it a value which happens to be of that same class.

Since wt is declared as a “WeightBox”, which is a subclass of “Box”, it is assignment compatible (the liskov substitution principle mentioned above). It’s no different than doing this:

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

Both ArrayList and LinkedList are assignment compatible with List.

If you ever want to check this at runtime, it’s a simple operation on the class itself:

Box.class.isAssignableFrom(WeightBox.class)

0

solved Size difference between base class and derived class