Interfaces

From Wikibooks, open books for an open world
Jump to: navigation, search

Creating Objects Java Programming
Interfaces
Using Static Members
Navigate Classes and Objects topic: v  d  e )

[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:

Computer code
class MyObject
{
 ...
}

When you type the above code, it actually means the following:

Computer code
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.


Computer code
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
  ...
}

...

Computer code
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.

[edit] External links

Clipboard

To do:
Add some exercises like the ones in Variables

Creating Objects Java Programming
Interfaces
Using Static Members
Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
In other languages
Sister projects
Print/export