0

Below is a simple program that I have:

interface X {}

public class Y implements X {
    public static void main(String[] args) {
        X x = new Y();
    }
}

Now, as far as I know, the variable x would be able to hold an object type of Y if an is-a relationship existed between Y and X. That is to say that class Y is a type of interface X.

But we know that interfaces cannot be instantiated and cannot have constructors. Does the compiler then create a constructor for the interface in the .class file ?

Moses
  • 611
  • 5
  • 20

1 Answers1

5

But we know that interfaces cannot be instantiated and cannot have constructors. Does the compiler then create a constructor for the interface in the .class file ?

No.

You are not instantiating X here, you are instantiating object Y and you are assigning it to X, because Y is of type X.

The paradigm is called as programming to interfaces.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307