Java Reference
In-Depth Information
Chapter 17
Interfaces
In this chapter, you will learn
What interfaces are
•
•
How to declare interfaces
•
How to declare abstract, default, and static methods in interfaces
•
How to fully and partially implement interfaces in a class
•
How to evolve interfaces after they are published
•
How to inherit an interface from other interfaces
instanceof
operator with interfaces
What marker interfaces are
•
Using the
•
•
How interfaces can be used to implement polymorphism
•
How dynamic binding applies to method calls on interface type variables
What Is an Interface?
The interface is a very important concept in Java programming. The knowledge of a Java developer is incomplete
unless he understands the role of interfaces in Java programming. It is better understood by examples than by a
formal definition. Let's discuss a simple example that will set the stage for the detailed discussion about the need for
interfaces, before I provide its formal definition.
A Java application consists of interacting objects. An object interacts with other objects by sending messages. The
ability of an object to receive messages is implemented by providing methods in the object's class. Suppose there is a
class called
Person
, which provides a
walk()
method. The
walk()
method gives the ability to receive a “walk” message
to every object of the
Person
class. Let's define the
Person
class as follows:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void walk() {
System.out.println(name + " (a person) is walking.");
}
}