• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Inner Class Doubt

 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Source: Devaka Cooray's Exam Simulator




I am not able to understand why Line-4 is generating a compiler error?
 
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Abhi, when you create the anonymous class instance it can only pass the Is-A test for Serializable, so the compiler will catch that it can never be cast to C. You could do it the other way around though (I think, you can try this and see if it works)

Serializable s = (Serializable) new C(){};

In this case, the instance of the anonymous class would pass the Is-A test for C, which itself passes the Is-A test for Serializable, so the cast would both compile and run.
[ December 28, 2008: Message edited by: Ruben Soto ]
 
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This happends as Anonymous class has no syntax to say it extends C implements Serializable.


class C_serializable extends C implements Serializable{
}



Above case is not possible in case of anonymous class, compiler can see this, will find that in

c=(C)new Serializable(){}; //Line-4



this scenario there is no way that this innerclass could be a child of class C.
 
Hang a left on main. Then read this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic