2

First of all, I learned that:

  • You cannot instantiate an Interface
  • An Interface doesn't implement its functions

After seeing the following Java code:

public class MyClassTest {

    public static void main(String[] args) {

        // String to CharSequence?

        CharSequence c = "Java";

        System.out.println(c);
        System.out.println(c.length());
    }
}

I am very confused when I learned that CharSequence is an Interface

  • How can you use an Interface like an object and initialize it?

  • Why does CharSequence implements a length function if its an interface?

user103214
  • 3,238
  • 5
  • 23
  • 35
  • Related: http://stackoverflow.com/questions/11323962/exact-difference-between-charsequence-and-string-in-java – Idos Jul 28 '16 at 07:55

1 Answers1

5

"Java" is an instance of the String class, which implements the CharSequence interface, which includes implementing the length() method. Therefore you can assign it to a CharSequence variable.

A variable whose type is an interface can be assigned references to instances (objects) of any classes that implement that interface.

Eran
  • 374,785
  • 51
  • 663
  • 734