简体   繁体   中英

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?

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

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

因为B <A,所以它不能创建一个等于B的新A.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM