Reputation: 35
CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
if CharSequence
is an interface then, in the above example aren't we instantiating a interface?
Upvotes: 3
Views: 994
Reputation: 311
CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
Here only the declared type of the reference variable is an interface, which is alright.
But the objects in the array are String objects - whose class implements the CharSequence interface.
Say, CharSequence[] items = { new Charsequence() } would result in compilation error
whereas
CharSequence[] items = { new someclass() }
where
class someclass implements CharSequence {
//
}
is totally fine
Upvotes: -1
Reputation: 2774
Here is a similar example using custom classes:
interface A{}
class A1 implements A{}
class A2 implements A{}
class A3 implements A{}
public class B {
A[] items = {new A1(),new A2(), new A3()};
}
Here each object in items
is actually of the implementing type (A1,A2,A3) rather than A
itself.
In your example something like this would also have been possible:
CharSequence[] items = {"Google",new StringBuffer("Apple"), new StringBuilder("Microsoft")};
Upvotes: 0
Reputation: 97322
You're instantiating a String
array and then assigning it to variable that has a CharSequence
array type. This works because String
is assignable to (implements) CharSequence
. Here's a couple more examples:
CharSequence cs = "Whatever";
List<Integer> list = new ArrayList<>();
So you're actually instantiating concrete types and assigning them to a variable/field that has an interface type.
Upvotes: 2