Interfaces
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:
![]() |
class MyObject extends Object // The compiler adds 'extends Object'. if not specified
{ ... } |
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.
![]() |
public interface MyInterface
{ public static final String CONSTANT = "This value can not be changed"; public String methodOne(); // This method must be implemented by the class implementing this interface ... } |
...
![]() |
public class MyObject implements MyInterface
{ // Implement MyInterface interface public String methodOne() { ... } } |
All constants are assumed to be final
static
and all methods public
, even if the keywords are missing.