Well, since I’m typing this from mobile I can’t type or copy paste the whole code hence I’m linking to the SO post –> What is the error in this code? Interview
If you do
X a = new Y();
it compiles. An interviewer asked how is this possible? I know this will be possible if X was defined as abstract class, but that isn’t the case either.
To expand on Branko Dimitrijević’s answer, this is possible because of the Liskov substitution principle.
In your comment, you said
It’s true that the base class and the derived class have their own member definitions, but they are not entirely distinct and different. Specifically, every member of the base class is also a member of the derived class. For example, you can always say
You can do that because every object has ToString, GetHashCode, and GetType methods, because every object’s runtime type inherits either directly or indirectly from object.
You can do the same with a base class other than object:
Then it’s perfectly legal to say
But of course, you can’t say
In order to use the Question property, you need to have a reference of type Y.
To recap: because every member of the base class is also a member of the derived class, you can use an instance of the derived class as if it were an instance of the base class. The derived class instance has all of the members of the base class.
You raised the subject of abstract classes. An abstract class cannot be instantiated, of course; you can only instantiate a class derived from the abstract class. That doesn’t affect the substitution principle, however, except to imply that a variable whose type is an abstract class must refer to an instance of a derived type, while a variable whose type is a non-abstract (unsealed) class may refer to an instance of a derived type.