From The Java Tutorials:
In Java, a class can inherit from only one class but it can implement more than one interface. Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement. This means that 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.
Can anyone provide me a basic pseudo type for this. I did not understand the bold lines.
You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types.
Any class that implements each of the methods listed in the interface can declare that it implements the interface and wear, as its merit badge, an extra type—the interface's type. Interface types act like class types.
An interface type is an abstract tagged type that provides a restricted form of multiple inheritance. A tagged type, task type, or protected type may have one or more interface types as ancestors.
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 { }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With