Suppose I have a class hierarchy.
At the head of the hierarchy is class A, followed by B, C, and so on. Inherited from each other.
Is it appropriate to do this?
A obj = new B(); //(Расширение) B obj = new A(); //(Сужение)
Suppose I have a class hierarchy.
At the head of the hierarchy is class A, followed by B, C, and so on. Inherited from each other.
Is it appropriate to do this?
A obj = new B(); //(Расширение) B obj = new A(); //(Сужение)
You can not assign ancestor heir. Only if you ancestor (a pointer to an ancestor object) previously assigned a pointer to a descendant object, then you can do the reverse assignment.
UPD
class A { ... } class B extends A { ... } ... B b = new B(); A a = b; // можно B c = (B) a; // можно A a1 = new A(); B b1 = a1; // нельзя
Think differently. Expansion-narrowing is too abstract.
The derived type is always a more specific variant of the base type. Let instead of the base type be “Fish”, and instead of the derivative - “Herring”.
Then it is clear what to write
Рыба р = new Селёдка();
possible: your р
- fish, for example, herring, why not.
But write the opposite:
Селёдка с = new Рыба();
you can not: the fish is not necessarily herring, right?
You can use type conversion:
// у вас есть какая-то рыба Рыба р; // тут много кода // а здесь вы точно знаете, что ваша рыба на самом деле селёдка // тогда можно использовать приведение типов Селёдка с = (Селёдка)р; // но если вы ошиблись, и в прошлой строке рыба была на самом деле // акулой, вы получите exception
How to check if your fish is herring? This is not necessary: Селёдка
Рыбы
heir, that is, each Селёдка
necessarily Рыба
.
How to check if your fish is herring? Very simple:
Рыба р; // много кода if (р instanceof Селёдка) { // о, оказывается, наша рыба -- селёдка! Селёдка с = (Селёдка)р; // здесь исключения не будет }
Source: https://ru.stackoverflow.com/questions/166875/
All Articles