aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark ""=" oprator question" Watch ""=" oprator question" New topic
Author

"=" oprator question

Shaily Sharma
Ranch Hand

Joined: Sep 10, 2007
Posts: 39
Hi,
Given:
11. class ClassA {}
12. class ClassB extends ClassA {}
13. class ClassC extends ClassA {}
and:
21. ClassA p0 = new ClassA();
22. ClassB p1 = new ClassB();
23. ClassC p2 = new ClassC();
24. ClassA p3 = new ClassB();
25. ClassA p4 = new ClassC();
Which three are valid? (Choose three.)
A. p0 = p1;
B. p1 =p2;
C. p2 = p4;
D. p2 = (ClassC)p1;
E. p1 = (ClassB)p3;
F. p2 = (ClassC)p4;
Answer: AEF

this is a mock exam question. I am not convinced with the answer.
"=" oprator for object references connotes to equivalence of object the reference variable pointing to... if both are pointing to same object then they can be said equal. as per this understanding how p0=p1 is valid answer?
Sandip Sarkar
Ranch Hand

Joined: Nov 25, 2007
Posts: 55
Hi Shaily,

p1 is an instanceof ClassA and hence can be easily assigned to p0.

p3 and p4 are nothing but references of ClassA and can be assigned using respective casts.

and remember there is a difference between incompatable types and inconvertable types.

Thanks.
Marc Peabody
pie sneak
Sheriff

Joined: Feb 05, 2003
Posts: 4727

The question isn't asking which references are equal. The question would use == (double equals) if it were asking about equality. In any case, none of those would be true because they all refer to different object instances.

What the question is testing is if you understand a legal assignment. If you have a Cat variable, you can't assign a Dog object to it. If you had an Animal reference, you could assign either a Cat or a Dog to it, assuming Cat and Dog both extend Animal (or implement Animal if Animal is an interface). In some cases, you know the type of object is a Cat even though you're currently using an Animal reference to point to it - so you could legally cast the variable to a Cat and then point to it using an actual Cat variable. I'm sure your book explains how all this works in more detail.


A good workman is known by his tools.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14423
    
  23

Shaily, please quote your sources. Note that just saying "this is a mock exam question" is not enough. Say from which mock exam you got this question.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: "=" oprator question