|Navigate Classes and Objects topic: )|
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
Interface is different from a class in several ways, including:
- You cannot instantiate an interface.
- An interface does not contain any constructors.
- All of the methods in an interface are abstract.
- An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both
- An interface is not extended by a class; it is implemented by a class.
- An interface can extend multiple interfaces.
Java does not allow you to create a subclass from two classes. There is no multiple inheritance. The major benefit of that is that all Java objects can have a common ancestor. That class is called
Object. All Java classes can be up-casted to
|Code section 4.16: Class declaration.
When you type the above code, it actually means the following:
|Code section 4.17: Class extension.
So, it can be guaranteed that all the
Object class methods are available in all Java classes. This makes the language simpler.
To mimic multiple inheritance, Java offers interfaces, which are similar to abstract classes. In interfaces all methods are abstract by default, without the
abstract keyword. Interfaces have no implementation and no variables, but constant values can be defined in interfaces. However, a single class can implement as many interfaces as required.
|Code section 4.18: Interface declaration.
|Code section 4.19: Interface implementation.
- 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.
When implementing interfaces there are several rules:
- A class can implement more than one interface at a time.
- A class can extend only one class, but implement many interfaces.
- An interface can extend another interface, similar to the way that a class can extend another class.