• Post Reply Bookmark Topic Watch Topic
  • New Topic

Declare a class in an interface  RSS feed

 
shashikant nagavarapu
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
The question I have is when I write an interface and declare a class init compiles well. Why is it so ? If it is ok to write so then in what situations do we write such a piece of code. Also how to access the members inside a class or the class, as we can only impement an interface , we cannot extend it.


Thanks and Regards
Shashikant
 
Nikhil Goel
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all declaring class in the interface breaks the inheritance concept that Interfaces are purely used as Types .

Now coming to ur question . It will compile no doubt abt it as it is an inner class to that class .

On accessing part u can access it as u access constants in Interfaces .<<Interfaces.ClassName>>. One imp thing though this class should be public & static .

Hope it helps
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by shashikant nagavarapu:
when I write an interface and declare a class init compiles well. Why is it so?


Because it is allowed. This compiles:


Originally posted by shashikant nagavarapu:
If it is ok to write so then in what situations do we write such a piece of code.


This is a completely different question, a question of good design. I don't know if I've ever seen a class definition nested inside an interface.

I take that back -- XMLBeans ( http://xmlbeans.apache.org/ ) does this to have static factory methods closely associated with an interface:


Originally posted by shashikant nagavarapu:
Also how to access the members inside a class or the class, as we can only impement an interface , we cannot extend it.


I don't understand you. Nesting within an interface is just a matter of name scoping. Nested classes and interfaces are implicitly "static":
[CODE]
interface D {
class E {}
interface F {}
}

//elsewhere:
D.E e = new D.E();
e.someEMethod();
 
shashikant nagavarapu
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Thanks for the replies. I tried it out and it compiled fine,and I also used it in an example. I actually wanted to know the purpose of writing such code and are there any other implications. Anyway thanks all for replying.


Thanks and Regards
Shashikant
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!