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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "from a mock exam" Watch "from a mock exam" New topic
Author

from a mock exam

marie m
Greenhorn

Joined: Sep 27, 2000
Posts: 7
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

Joined: Sep 14, 2000
Posts: 121
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).]


SCJP
Pragya Prakash
Ranch Hand

Joined: Sep 18, 2000
Posts: 42
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

Joined: Sep 27, 2000
Posts: 7
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...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: from a mock exam