• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Copy the class obj into Interface

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Rancher
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic