Interface as a type in Java?
Consider the following example:
Serializable s = new ArrayList();
In Java, this is valid code, even though Serializable
is an interface, because ArrayList
implements Serializable
. So in this case, we're treating s
as a variable of type Serializable
.
Now suppose we follow up the above code with the following:
s = "String object";
This is also valid becauseString
also implements Serializable
. Since we declared s
as type Serializable
, it can point to any object that implements that interface.
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 { }