Object inheritance and method parameters/return types - Please check my logic
- by user2368481
I'm preparing for a test and doing practice questions, this one in particular I am unsure I did correctly:
We are given a very simple UML diagram to demonstrate inheritance: I hope this is clear, it shows that W inherits from V and so on:
|-----Y
V <|----- W<|-----|
|-----X<|----Z
and this code:
public X method1(){....}
method2(new Y());
method2(method1());
method2(method3());
The questions and my answers:
Q: What types of objects could method1 actually return?
A: X and Z, since the method definition includes X as the return type and since Z is a kind of X is would be OK to return either.
Q: What could the parameter type of method2 be?
A: Since method2 in the code accepts Y, X and Z (as the return from method1), the parameter type must be either V or W, as Y,X and Z inherit from both of these.
Q: What could return type of method3 be?
A: Return type of method3 must be V or W as this would be consistent with answer 2.