开发者

Need Inheritance Relationships explained

I am not looking for you to give me the answer to this, I am simply asking for explanations to give me an understanding of how I can find the answer.

Assume we have a project of four classes A, B, C and D. We have the following variables:

A a; B b; C c; D d;

The following assignments are all legal (They all compile):

a = b; a = c; d = b;

The following assignments are illegal (They cause compiler errors):

c = d; d = c; d = a;

Draw the i开发者_C百科nheritance relationships between these classes.

Help is appreciated, thanks :)


A legal assignment means that the class of the variable on the left side is a superclass of the class on the right side.

a = b means b is somewhere in the subclass hierarchy of a, or in other words, a is an ancestor of b.

If it doesn't compile, it means that that is not a valid assignment.

From your "legal" assignment, you can infer that b is a subclass of a, c is a subclass of a and b is a subclass of d.

Hopefully, this should give you enough to go on.


Here is a method that you might use to develop your diagram. Draw every possible inheritance line between the set of four classes. If an assignment is legal, then the inheritance line(s) corresponding to that relationship can be marked as valid. If an assignment is illegal, then the inheritance line(s) corresponding to that relationship can be removed. Once your done, the remaining lines should contain the final inheritance map.


If a class X inherits from class Y, it is possible to assign an object x to a variable of the type Y, like this:

y = x;

If 2 classes do not inherit this is not possible and you get a compile error.

Side note: This would mean that you can only access the methods of Y even though it is still still an object of the class X.


Here's a hint: There is only one valid hierarchy that meets the given constraints.

Draw a directed acyclic graph. If an assignment is valid, draw an arrow from the type of the value being assigned (the right side) to the type of the variable which is assigned (the left side). If the assignment is invalid, there's no arrow in that direction. This will produce something that looks like UML, where an arrow from a derived class points to its superclass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜