How do you solve the problem (Java, inheritance)?
Given the following Java source code, which uses four classes (O, X, T and M) and creates an object of each class.
O o = new O();
X x = new X();
T t = new T();
M m = new M();
The following assignments are all legal (they can be translated):
m = t; m = x; o = t;
The following assignments are all illegal (they lead to translation errors):
o = m; o = x; x = o;
a) What can you say about the inheritance relationships between these classes?
(My guess, but I don't know why: T inherits from M, X inherits from M, T inherits from O)
b) Give a UML diagram of the inheritance hierarchy and explain why.
Can someone please tell me how to solve a problem like this?
thanks in advance
You only have to understand polymorphy and inheritance for this task.
Let’s say there are these two classes that are in a parent-child relationship:
The subclass elephant inherits all methods and properties that can be accessed from the outside Animal.
In this sense it is also legitimate to say that an elephant corresponds to an animal.
That doesn’t work otherwise. Not every animal is also an elephant. Only the elephant knows how to comfort.
For the second part of the task, you can add the Wikipedia article Class diagrams use. Relevant to you is the Generalization.
Thank you. So my guess in task a) was right? The task with the UML is not really a problem of specialization and generalization I understand as far as
Your solution is right in itself, but there is still something missing. T fits in O and M, but can only inherit directly from one basic class (or one class can only have one, not several basic classes). This means between O and M there is another inheritance relationship.
Thank you!
That’s right.
So O inherits from M and T from O?
No, O is a basic class T.
To describe it again with simpler names:
An African elephant is both an elephant and an animal. An elephant is an animal. All these assignments therefore work:
Class T is synonymous with the African elephant. Where M and O in this inheritance chain, you can determine the illegal rules.
Don’t come on.
Would that be UML?
M|
^
|
| T | X |
^
|
| O|