Java Programming/Interfaces
From Wikibooks, the open-content textbooks collection
| Navigate Classes and Objects topic: |
[edit] 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 Object. Example:
class MyObject
{
...
}
When you type the above code, it actually means the following:
classMyObjectextendsObject // -- The compiler adds 'extends Object'. if not specified { ... }
So it can be guaranteed that certain 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 key word. 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.
publicinterface MyInterface {publicstaticfinalStringCONSTANT = "This value can not be changed";publicStringmethodOne(); // This method must be implemented by class who implements this interface ... } ...publicclassMyObjectimplementsMyInterface { // --- Implement MyInterface interfacepublicStringmethodOne() { ... } }