Java Programming/Interfaces

From Wikibooks, open books for an open world
Jump to: navigation, search
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:

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

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 that implements this interface
  ...
}

...

public class MyObject implements MyInterface
{
  // Implement MyInterface interface 
  public String methodOne()
  {
   ...
  }
}

[edit] External links

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