Java can implement how many interfaces




















An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. Definition: An interface is a named collection of method definitions without implementations. Because an interface is simply a list of unimplemented, and therefore abstract, methods, you might wonder how an interface differs from an abstract class. The differences are significant.

Let's set up the example we'll be using in this section. Suppose that you have written a class that can watch stock prices coming over a data feed. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. The interface keyword is used to declare an interface. An interface is implicitly abstract.

You do not need to use the abstract keyword while declaring an interface. When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. An implementation class itself can be abstract and if so, interface methods need not be implemented. An interface can extend another interface in the same way that a class can extend another class.

If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should implement Relatable. Any class can implement Relatable if there is some way to compare the relative "size" of objects instantiated from the class. For strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For planar geometric objects, area would be a good choice see the RectanglePlus class that follows , while volume would work for three-dimensional geometric objects.

All such classes can implement the isLargerThan method. If you know that a class implements Relatable , then you know that you can compare the size of the objects instantiated from that class. Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable.



0コメント

  • 1000 / 1000