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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.