Rishabh Ohri
Rishabh Ohri

Reputation: 1310

Why cannot a derived class refer the base class?

class A
{
}

class B : A
{
}

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

Upvotes: 4

Views: 317

Answers (4)

Subash
Subash

Reputation: 61

A is a base, you derived B from A. A is like as base for build, based on base you can build new floors. But using floor u cant build base.

Upvotes: 1

Happy Flight
Happy Flight

Reputation: 19

Because B < A, so it cant create a new A that is equal to B

Upvotes: 1

Martin Gunia
Martin Gunia

Reputation: 1141

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();

Upvotes: 7

Davide Piras
Davide Piras

Reputation: 44605

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 ;-)

Upvotes: 17

Related Questions