aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Object Reference Casting" Watch "Object Reference Casting" New topic
Author

Object Reference Casting

Frank Albright
Greenhorn

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
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
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
Greenhorn

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.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
If line #3 weren't there, would this execute (compile and run) successfully?
Anonymous
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
Supree
Greenhorn

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;
};
 
Don't get me started about those stupid light bulbs.
 
subject: Object Reference Casting
 
Similar Threads
Object referernce casting
casting between a ref type and an array.
ClassCastException
type casting
answer please