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

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
8 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
regex9
1 year ago

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:

class Animal {
  public void run() {
  }
}

class Elephant extends Animal {
  public void toot() {
  }
}

The subclass elephant inherits all methods and properties that can be accessed from the outside Animal.

Elephant dumbo = new Elephant();
dumbo.run();

In this sense it is also legitimate to say that an elephant corresponds to an animal.

Animal dumbo = new Elephant();
dumbo.run();

That doesn’t work otherwise. Not every animal is also an elephant. Only the elephant knows how to comfort.

Elephant dumbo = new Animal(); // error
dumb.toot();

For the second part of the task, you can add the Wikipedia article Class diagrams use. Relevant to you is the Generalization.

regex9
1 year ago
Reply to  Klaus820

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.

regex9
1 year ago

That’s right.

regex9
1 year ago

No, O is a basic class T.

To describe it again with simpler names:

Animal > Elephant > African (Savanna) Elephant

An African elephant is both an elephant and an animal. An elephant is an animal. All these assignments therefore work:

Animal animal = new AfricanElephant();
Elephant animal2 = new AfricanElephant();
Animal animal3 = new Elephant();

Class T is synonymous with the African elephant. Where M and O in this inheritance chain, you can determine the illegal rules.