my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Object Reference Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Object Reference Casting" Watch "Object Reference Casting" New topic

Object Reference Casting

Frank Albright

Joined: Feb 19, 2000
Posts: 23
MySub is a subclass of Mybase:
1. MyBase objBase = new MyBase();
2. MySub objSub = new MySub();
3. objBase = objSub;
4. objSub = (MySub)objBase;
The cast in line 4 is definately required at compile time. I had a option on the exam that asked if this was ok at runtime or possibly a runtime error. Which is it? The runtime rules for object reference casting state that the class of the expression being converted must be the "NewType" or must inherit from "NewType". Here "NewType would be the MySub class. This means that objBase must be the class MySub or a subclass of MySub. Does objBase take the class of objSub in line 4? I'm really confused now!
Tony Alicea

Joined: Jan 30, 2000
Posts: 3226
Since objBase can denote an object of class MySub, a cast is needed for compilation but only at runtime will we know if it will fail. It will fail if in fact objBase is denoting an object of class MyBase.

Tony Alicea
Senior Java Web Application Developer, SCPJ2, SCWCD
Chuck Lan

Joined: Feb 17, 2000
Posts: 6
It is okay at runtime because objBase is a reference to a MySub object, which is a subclass of MyBase. So casting the object to MySub class is okay.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
If line #3 weren't there, would this execute (compile and run) successfully?
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
If line 3 were removed the code would compile but wouldn't run since objBase is still referencing a MyBase object and objSub expects to have a reference to a MySub object. At run time you will get a ClassCastException. Regards, Joe

Joined: Feb 25, 2000
Posts: 27
Hi Frank,
I had the same confusion.
But I tested it. It compiles and runs fine.
Pl test this code.
class test1 {};
public class test2 extends test1 {
public static void main(String args[])
test1 tt1 = new test1();
test2 tt2 = new test2);
tt2 = tt1;
tt1 = (test1)tt2;
I agree. Here's the link:
subject: Object Reference Casting
It's not a secret anymore!