Java Reference
In-Depth Information
Interfaces
Interfaces, like abstract classes and methods, provide templates of behavior that other
classes are expected to implement. They also offer significant advantages in class and
object design that complements Java's single inheritance approach to object-oriented pro-
gramming.
The Problem of Single Inheritance
As you begin turning a project into a hierarchy of classes related by inheritance, you
might discover that the simplicity of the class organization is restrictive, particularly
when you have some behavior that needs to be used by classes that do not share a com-
mon superclass.
Other object-oriented programming (OOP) languages include the concept of multiple
inheritance, which solves this problem by letting a class inherit from more than one
superclass, acquiring behavior and attributes from all its superclasses at once.
This concept makes a programming language more challenging to learn and to use.
Questions of method invocation and how the class hierarchy is organized become far
more complicated with multiple inheritance and more open to confusion and ambiguity.
Because one of the goals for Java was that it be simple, multiple inheritance was rejected
in favor of single inheritance.
A Java interface is a collection of abstract behavior that can be adopted by any class
without being inherited from a superclass.
An interface contains nothing but abstract method definitions and constants—there are
no instance variables or method implementations.
Interfaces are implemented and used throughout the Java class library when behavior is
expected to be implemented by a number of disparate classes. Later today, you'll use one
of the interfaces in the Java class hierarchy, java.lang.Comparable .
Interfaces and Classes
Classes and interfaces, despite their different definitions, have a great deal in common.
Both are declared in source files and compiled into .class files. In most cases, an inter-
face can be used anywhere you can use a class (as a data type for a variable, as the result
of a cast, and so on).
You can substitute an interface name for a class name in almost every example in this
book. Java programmers often say “class” when they actually mean “class or interface.”
Interfaces complement and extend the power of classes, and the two can be treated
almost the same, but an interface cannot be instantiated: new only can create an instance
of a nonabstract class.
 
Search WWH ::




Custom Search