• Post Reply Bookmark Topic Watch Topic
  • New Topic

Copy the class obj into Interface  RSS feed

 
sudha swami
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I need to copy the class(A) obj a1 into interface (B).

B obj = (B)a1

Is this correct.

sudha
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you've shown is casting. Let's expand it a bit to make sure we're on the same page:

Because B extends A, somebody could create an instance of B and pass it to myMethod. Inside myMethod, I'm so confident that this really is an instance of B, I use casting to tell the compiler to trust me and let me make my obj variable refer to a1.

What if I'm wrong and somebody calls myMethod with an instance of A? I've convinced the compiler to let me try this, and it won't get caught until runtime. Then I'll get a class cast exception.

Now, since you said "copy" instead of "cast" I'm not sure this is even what you wanted to know. Is it close?
 
Pat Farrell
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean by "copy"?

In java, usually you have to call .clone() to make a real copy, what your code does is simply make another reference to the same object, not have two objects.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!