File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object Reference Casting

 
Frank Albright
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3226
5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chuck Lan
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
If line #3 weren't there, would this execute (compile and run) successfully?
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
};
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic