wood burning stoves*
The moose likes Java in General and the fly likes Can I instantiate an Interface? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Can I instantiate an Interface?" Watch "Can I instantiate an Interface?" New topic
Author

Can I instantiate an Interface?

Jane Somerfield
Ranch Hand

Joined: Jul 20, 2002
Posts: 193
The answer is No. But I can do this

List<int> l = new List<int>();

Why?
Hebert Coelho
Ranch Hand

Joined: Jul 14, 2010
Posts: 754

When you do new List<Integer>(){...}; you create a anonymous class. [=

http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm
http://mindprod.com/jgloss/anonymousclasses.html

[uaiHebert.com] [Full WebApplication JSF EJB JPA JAAS with source code to download] One Table Per SubClass [Web/JSF]
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3071
    
  33

Can you really compile that code?


Mohamed Sanaulla | My Blog
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3071
    
  33

Creating an anonymous inner class is nothing but implementing that particular interface and you would have to implement all the methods present in the interface.

The given code is no where close to that. Moreover the type used in the Generic declaration has to be a class/reference type.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Mohamed Sanaulla wrote:Can you really compile that code?

It won't. Even if there were a non-abstract List class with a generic type (java.util.List is an interface, java.awt.List is not generic), the <int> is still not allowed because primitive types can never be generic types.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jane Somerfield
Ranch Hand

Joined: Jul 20, 2002
Posts: 193
Sorry, the code does not compile. My question was can we use primitive in generics.
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3071
    
  33

Jane Somerfield wrote:Sorry, the code does not compile. My question was can we use primitive in generics.

I think Rob just mentioned about this in his post and also I have mentioned it in my second post.

I was struggling to remember the "primitive" keyword though
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7892
    
  21

Jane Somerfield wrote:My question was can we use primitive in generics.

No.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can I instantiate an Interface?