• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Conversion question

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
interface I1 {} interface I2 {}
class Base implements I1 {}
class Sub extends Base implements I2 {}
class Yellow {
public static void main(String args[]) {
Base base = new Sub(); // 1
I1 i1 = base; // 2
Sub sub = (Sub)base; // 3
I2 i2 = (Sub)base; // 4
}}

I have doubt on line 4 . How base is getting assigned to i2 as i see there is no relation between base and I2.

Please explain.
 
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I2 i2 = (Sub)base; // 4



Hi gunjan,
Your casting the base to sub and then passing it to i2 and sub implements interface 2
 
Gunjan Kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ok but i thought first i am assigning and then casting .

anyway thanks
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by gkcom gk:

Base base = new Sub(); // 1
I1 i1 = base; // 2
Sub sub = (Sub)base; // 3
I2 i2 = (Sub)base; // 4
}}

I have doubt on line 4 . How base is getting assigned to i2



Base is NOT assigned to i2. The OBJECT base is referring to is assigned to i2. This object is of class Sub which implements I2.

Another option would be to cast base to I2:

I2 i2 = (I2) base; // 4

HTH,
Regards,
Rick
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic