문제

it's simple, i just want a explanation about this:

internal class B { // Base class
}
internal class D : B { // Derived class
}

in other class I wrote:

B b3 = new Object(); //compilation time error!

why??? We suposse that all classes inherit from "object"

도움이 되었습니까?

해결책

B is more specialized than Object, therefore you cannot assign an Object instance to a B reference. This is because not every Object is actually a B - only the opposite is true.

Let's assume that you have a field x in the class B. When you instantiate an Object, no memory is reserved for this field, and if you could assign it to a reference of type B, it would therefore try to read or write to unallocated memory, which is not allowed (or useful).

다른 팁

All classes are objects, but not all objects are {someclass}.

In a similar way, all buses are vehicles, but not all vehicles are buses.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top