Interface as a type in Java?

Let’s declare two interfaces and a class that implements them both:

interface I1 { }

interface I2 { }

class C implements I1, I2 { }

objects can have multiple types

In the following code, it can be seen that a C instance has the type of C as well as I1 and I2:

C c = new C();

boolean isC = (c instanceof C);   //true
boolean isI1 = (c instanceof I1); //true
boolean isI2 = (c instanceof I2); //true

Now let’s declare a class B which implements I1 as well:

class B implements I1 { }

if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface.

If we declare a variable of type I1, we can set it to an instance of C, and then reassign it to an instance of B:

I1 i1 = new C();
i1 = new B();

We can also reassign it to an instance of D, where D extends C:

i1 = new D();


class D extends C { }

Leave a Comment