• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assignment Question

 
Paul Salerno
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Class B extends A
2. B b1 = new B()
3. A a1 = new A()
4. a1 = b1
5. b1 = (B)a1
since declared type a1 "is a" A assigned an actual type of B the assignment on line 5 will compile and run, w/ cast always necessary.
I want to be absolutely sure that this is correct (I have conflicting notes), so that I can close this topic.
Thanks
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you got it Paul
if you try to compile and run your code, you'd definitely get the answer to your question
If you remove the cast to B you will not be able to compile the code.
[ February 08, 2002: Message edited by: Valentin Crettaz ]
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the perfect thing to try with your compiler!!
 
Paul Salerno
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I appreciate it guys, you all must think alike
 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
at line 5 the cast takes care of compiling, but if you run it will give you a runtime error ?

Originally posted by Paul Salerno:
1. Class B extends A
2. B b1 = new B()
3. A a1 = new A()
4. a1 = b1
5. b1 = (B)a1
since declared type a1 "is a" A assigned an actual type of B the assignment on line 5 will compile and run, w/ cast always necessary.
I want to be absolutely sure that this is correct (I have conflicting notes), so that I can close this topic.
Thanks
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by mark stone:
at line 5 the cast takes care of compiling, but if you run it will give you a runtime error ?


In this case, it won't because the variable a1 contains a reference to a valid B object when the assignment b1 = (B) a1; is done. If, however, the variable a1 referenced an object of type A, the compiler would allow this but it would throw a ClassCastException at runtime.
Corey
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul,
since you haven't installed the JDK yet, you can go to the following link http://www.jdiscuss.com and click on the "Web compiler" link at the top of the window. That's a web compiler which allows you to test some code from within your browser. Be aware that it only works in IE browsers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic