Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

3.9. Interfaces

Like a class, an interface defines a new reference type. Unlike classes, however, interfaces provide no implementation for the types they define. As its name implies, an interface specifies only an API: all of its methods are abstract and have no bodies. It is not possible to directly instantiate an interface and create a member of the interface type. Instead, a class must implement the interface to provide the necessary method bodies. Any instances of that class are members of both the type defined by the class and the type defined by the interface. Interfaces provide a limited but very powerful alternative to multiple inheritance .[9] Classes in Java can inherit members from only a single superclass, but they can implement any number of interfaces. Objects that do not share the same class or superclass may still be members of the same type by virtue of implementing the same interface.

[9] C++ supports multiple inheritance, but the ability of a class to have more than one superclass adds a lot of complexity to the language.

3.9.1. Defining an Interface

An interface definition is much like a class definition in which all the methods are abstract and the keyword class has been replaced with interface. For example, the following code shows the definition of an interface named Centered. A Shape class, such as those defined earlier in the chapter, might implement this interface if it wants to allow the coordinates of its center to be set and queried:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint