SCJP 5.0
Love and Peace
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Originally posted by Ravikanth kolli:
hi Henry Zhi Lin ,
welcome to javaranch.
Can you mention the source for the program. As mentioned in this
SCJP 5.0
Originally posted by Steven Landers:
This is actually legal code -
Prior to Java 5, we were not able to change the return type for any return type of an overriding method. As of Java 5, an overriding method may return a subclass of the return type of the overridden method. This works because the retuned object is "reduced" to the type of its supertype - in this case, type A. So SubCovariantTest's getObject is running. In this example, the c1.getObject() is returning an object of type B, except it is returned in the type of it's supertype - type A.
In effect:
////////////////////////////////
Calling:
A myResultingA = c1.getObject() (this returns type B via a reference of type A)
is similar to:
List<Integer> myList = new ArrayList<Integer>();
////////////////////////////////////
Try casting the result of c1.getObject() - it should print 6. It also helped me to put a print statement in each method.
class A {
int x = 5;
}
class B extends A { int x = 6 }
public class CovariantTest {
public A getObject() { return new A(); }
public static void main(String[] args) {
CovariantTest c1 = new SubCovariabntTest();
System.out.println(((B)c1.getObject()).x);
}
}
class SubCovariantTest extends CovariantTest {
public B getObject() {
System.out.println("SubCovariantTest is running");
return new B();
}
}
In most of the exam questions I've run across, this isn't an issue, as we're just testing to see which method ran - and not what the effect of the return type really is.
Good luck! I have my test tomorrow - yikes.
[ November 04, 2008: Message edited by: Steven Landers ]
SCJP 5.0
SCJP 5.0
Thanks,<br />Subhasish
SCJP 5.0
blog: http://tunatore.wordpress.com
https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=spring39coupon
Core Spring Certified Professional + SCJP 6.0 + SCWCD 1.5
SCJP5 and SCWCD1.5
Think Twice Act Wise...
I guess this is downto the following statement
Object type (not the reference variable's type), determines which overridden
method is used at runtime.
Reference variable type (not the Object type), determines which instance variable is used at compile time.
Love and Peace
Arron,
Yes, you are right. Those statements in your quotes can be explained without bringing in covariance.
But, I am unable to understand why B b = c1.getObject(); does not compile without a (B) cast
SCJP5 and SCWCD1.5
Think Twice Act Wise...
Hi arron.
c1.getObject();
it will call the getObject method in the sub class because of overriding and it returns B object.
Uh no, no it does not, it returns 5.
Thanks,<br />Subhasish
SCJP5 and SCWCD1.5
Think Twice Act Wise...
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
SCJP5 and SCWCD1.5
Think Twice Act Wise...