Hi All,

Interfaces cannot be instantiated.
Could you please explain why the following is valid:

interface MyInterface{}
MyInterface[] myInterface = new MyInterface[]{"a", "b"};

Cheers!

Recommended Answers

ehm ... where do you get the idea this code is valid?

"a" and "b" are Strings, not instances of MyInterface, so this won't work. what would be valid, though, is:

MyInterface[] myInterface = new MyInterface[]{new MyInterface(){}, new MyInterface(){}};

here, it seems that you are instantiating the interface, but actually, …

Jump to Post

All 2 Replies

ehm ... where do you get the idea this code is valid?

"a" and "b" are Strings, not instances of MyInterface, so this won't work. what would be valid, though, is:

MyInterface[] myInterface = new MyInterface[]{new MyInterface(){}, new MyInterface(){}};

here, it seems that you are instantiating the interface, but actually, you are creating anonymous classes which implement the interface, which then you instantiate, you don't instantiate the interface itself.

Thanks stultuske. Actually you are right, I was confused with the new MyInterface, but I think get it since we dont have new MyInterface().
Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.