Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

from a mock exam

 
marie m
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
one of the mock exams had this question:
********
Consider the following class definitions:
class Base{}
class Subclass1 extends Base{}
class Subclass2 extends Base();
Now consider the following declarations:
Base b = new Base();
Subclass1 s1 = new Subclass1();
Subclass2 s2 = new Subclass2();
Now, consider the following assignment:
s1 = (Subclass1)s2;
Which of the following statements are correct regarding this assignment (select one).
********
the answer given was, The code fails to compile. The compiler complains that the assignment "s1 = (Subclass1)s2" is illegal.
********
my answer was, and i still feel this is true, that the code will compile (because of the explicit cast) but will return a runtime error (a ClassCastException or something) because the cast was illegal
any other opinions?
 
Stephen Pride
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Compiling the code use Java 1.2.2 gives me the following error message:
Invalid cast from SubClass2 to SubClass1.
s1 = (SubClass1)s2;

The main reason being that SubClass2 is not in SubClass1's parental heirarchy. IOW, going up SubClass1's heirarchy shows there is no SubClass2 class.
Regards,
SP
[This message has been edited by Stephen Pride (edited September 27, 2000).]
 
Pragya Prakash
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marie,
s1 = (Subclass1)s2;
It's true that the code fails to compile. The compiler complains that the assignment "s1 = (Subclass1)s2" is illegal.
I used the following code to test it.
class Subclass1 extends Base{}
class Subclass2 extends Base
{}
class Base{
public static void main() {
Base b = new Base();
Subclass1 s1 = new Subclass1();
Subclass2 s2 = new Subclass2();
/*iilegal:*/
s1 = (Subclass1)s2;
}
}
Some rules to remember about Object Reference Casting:-
Say u want to do this, legally:-
s1 = (SubClass1)s2;
Compile-time rule:-
Assuming both s1 & s2 are classes, one class must be a subclass of the other.

Run-time rule:-
s1 must be of type Subclass1 OR MUST inherit from SubClass1.
Hope this helps
Regards,
Pragya
 
marie m
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you're right - it did error in compile
now that just change my whole understanding of casting... i thought you could cast any object to any class with a runtime check...
i guess i need to review that topic again...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic