• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is this Java class feature? (interfaces)  RSS feed

 
David Tyson
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Java newbie here. I've been meaning to get stuck into Java again and then I stumbled upon some code that looked like this:



First of all, I didn't know that you could create new objects in class declarations that's not wrapped in a method (i.e. the constructor). Is there a name for this, and is it equivalent to just doing it in the constructor?

Secondly, I was surprised that you can create instances of interfaces. It's my understanding that since MyInterface is an interface, the only way to use it would be something like this, by making it into a class with concrete methods:


}

Instead, a new class was declared without using the implements keyword, and an instance of it was created and assigned to MyClass's rabbits attribute. I'm really not sure how this works; does the new operator on an interface do the same thing as the implements keyword? Is the class declaration for rabbits anonymous, because you can't make any more of them (unless you instantiate another MyClass)? Any clarification on what's happening here or links to more information would be greatly appreciated.
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line 12 is initializing an instance variable, and yes that is legal. You can't put a lot of code outside a method, but initializations are fine. The code runs at the time of construction.

Lines 22-26 are a little more complicated. You aren't instantiating an interface, which would in fact be illegal. You are defining an anonymous inner class that implements the interface, and then instantiating that. Anonymous inner classes are a useful feature of the Java language, especially for event handlers, but they do take some time to wrap your head around.
 
David Tyson
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Greg Charles for your quick reply! I will read up on anonymous inner classes then.

edit: I found a nice link which describes three ways anonymous inner classes can be used (2nd answer):

http://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!