GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing en.wikibooks.org — Interfaces - Wikibooks, open books for an open world
An interface is an abstraction of class with no implementation details. For example,
An interface represents a contract:
You can see that the
A class can implement several interfaces, separated by a comma. Java interfaces behave much like the concept of the Objective-C protocol. It is recommended to name an interface InterestIf you have objects from different classes that do not have a common superclass, you can't call the same method in those classes, even if the two classes implement a method with the same signature.
The solution is to write an interface that defines the method that should be implemented in the two classes as the
You can also implement this using a common super class but a class can only inherit from one super class whereas it can implement several interfaces. Java does not support full orthogonal multiple inheritance (i.e. Java does not allow you to create a subclass from two classes). Multiple inheritance in C++ has complicated rules to disambiguate fields and methods inherited from multiple superclasses and types that are inherited multiple times. By separating interface from implementation, interfaces offer much of the benefit of multiple inheritance with less complexity and ambiguity. The price of no multiple inheritance is some code redundancy; since interfaces only define the signature of a class but cannot contain any implementation, every class inheriting an interface must provide the implementation of the defined methods, unlike in pure multiple inheritance, where the implementation is also inherited. The major benefit of that is that all Java objects can have a common ancestor (a class called When overriding methods defined in interfaces there are several rules to be followed:
Extending interfacesAn interface can extend several interfaces, similar to the way that a class can extend another class, using the
This way, a class implementing the
Doing so, a Test your knowledge Question 4.2: Consider the following interfaces.
List all the methods that an implementing class of Answer
Question 4.3: Consider the following classes and the following code.
Change the implementation of the code in order to be able to uncomment the commented line without compile error. Answer You have to create an interface that defines the method
Now your code has to cast the objects to the
| |||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |