Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot a derived class refer the base class?

Tags:

c#

oop

class A
{
}

class B : A
{
}

I know that B b = new A(); is not possible, but what is the explanation behind it?

like image 423
Rishabh Ohri Avatar asked Nov 27 '22 22:11

Rishabh Ohri


2 Answers

it is simply because of the way inheritance works; A Woman or a Man is a Person and eventually adds something else like gender to the base class Person.

if you declare:

Man m = new Person()

than you got a Man with no Gender.

the other way works because every Man is also a Person ;-)

like image 110
Davide Piras Avatar answered Dec 15 '22 07:12

Davide Piras


By deriving from A, you specify that instances of B are not only B, they're A also. This is called inheritance in OOP. The power of inheritance is in being able to abstract away general properties/behaviour to a common class and then derive specialized classes from it. The specialized classes can change existing functionality (called overriding) or add new functionality.

However, inheritance works only in one direction, not both. Objects of class A cannot be treated as B because B may (and often does!) contain more functionality than A. Or, in other words, B is more specific while A is more general.

Therefore, you can do A a = new B(); but not B b = new A();

like image 39
Martin Gunia Avatar answered Dec 15 '22 05:12

Martin Gunia