سؤال

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