Assume the following declarations:
class MyClass { } class MyClass2 extends MyClass { } class MyClass3 extends MyClass2{ } class X{ /*from w w w.ja va2 s .co m*/ MyClass2 getMyClass2 (){ return new MyClass2 (); } } class Y extends X{ // method declaration here }
Which of the following methods can be inserted in class Y?
Select 2 options
A. public MyClass3 getMyClass2 (){ return new MyClass2 (); } B. protected MyClass2 getMyClass2 (){ return new MyClass3 (); } C. MyClass3 getMyClass2 (){ return new MyClass3 (); } D. MyClass getMyClass2 (){ return new MyClass (); }
Correct Options are : B C
For Option A.
Its return type is specified as MyClass3, but it is actually returning an object of type MyClass2.
Since MyClass2 is NOT a MyClass3, this will not compile.
For Option B.
Since MyClass3 is-a MyClass2, this is valid. Also, an overriding method can be made less restrictive.
protected is less restrictive than 'default' access.
For Option C.
Covariant returns are allowed in Java 1.5, which means that an overriding method can change the return type of the overridden method to a subclass of the original return type.
Here, MyClass3 is a subclass of MyClass2. So this is valid.
For Option D.
An overriding method cannot return a superclass object of the return type defined in the overridden method.
A subclass is allowed in Java 1.5.