File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"=" oprator question

 
Shaily Sharma
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 55
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4727
Mac Ruby VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic