3
CharSequence[] items = { “Google”, “Apple”, “Microsoft” };

if CharSequence is an interface then, in the above example aren't we instantiating a interface?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111

3 Answers3

2

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

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")};
Nikhil Talreja
  • 2,754
  • 1
  • 14
  • 20
-1

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

user3790568
  • 311
  • 2
  • 8