Creating Objects of Classes That Implement Interfaces
When you create an object of a class that implements an interface, the reference type can be the interface type. An interface defines a set of methods that a class agrees to implement, and any class that implements the interface must provide an implementation for each method. This makes it possible to write code that works with any class that follows the same interface.
Creating an Object
You can create an object of the implementing class just like any other object.
In this example:
- The reference type is
Circle. - The object type is
Circle.
Because the reference type and the object type are the same, you can use all of the methods in Circle.
Using an Interface Reference
You can also store the same object in a variable whose type is the interface.
In this example:
- The reference type is
Shape. - The object type is
Circle.
You can call methods that are part of the Shape interface.
However, you cannot call methods that belong only to Circle through a Shape reference.
The compiler only knows that shape is a Shape, so it only allows access to the methods declared in Shape.
Since shape references a Circle objects, it's an instanceof Circle, you can typecast shape to be a Circle to call methods of Circle.
Why Use an Interface Reference?
Using the interface as the reference type makes your code more flexible. Code that works with Shape objects does not need to change if another class is added that implements the interface. It can use any class that implements the interface.
For example, a method that accepts a Shape can work with a Circle today and another shape later, without changing the method itself.
Choosing the Reference Type
Use the implementing class as the reference type when you need behavior that is specific to that class.
Use the interface as the reference type when you only need the behavior shared by all classes that implement the interface or when you have a collection of objects where the classes all implement the same interface.