Why can't a derived class refer to a base class?

class A { } class B : A { } 

I know that B b = new A(); impossible, but what is the explanation for this?

+4
source share
4 answers

Having obtained from A , you indicate that the instances of B are not only B , but also A This is called inheritance in OOP. The power of inheritance is to abstract common properties / behavior with a common class, and then derive specialized classes from it. Specialized classes can modify existing functionality (called overrides) or add new functions.

However, inheritance only works in one direction, not both. Class A objects cannot be thought of as B , because B can (and often does!) Contain more functionality than A Or, in other words, B more specific, while A is more general.

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

+7
source

it's just because inheritance works; A Woman or Man is a Man and ultimately adds something like gender to the base class Person.

if you declare:

 Man m = new Person() 

than you have a person without gender.

another way works, because each Man is also a Man; -)

+17
source

Since B <A, therefore, he cannot create a new A that equals B

+1
source

A is the base, you received B from A. A as the basis for the assembly, based on the base, you can build new floors. But using the base base for the foundation, you can

+1
source

Source: https://habr.com/ru/post/1369273/


All Articles