J2EEOnline J2EEOnline


Java Basics  «Prev  Next»
Lesson 7Interfaces
ObjectiveDefine role of Java Interfaces

Define Role of the Java interface

  1. Describe the role of an interface and identify when to use one.
  2. Implement an interface.

Java allows multiple inheritance of interface, but not multiple inheritance of implementation. You can define an interface in Java to take advantage of multiple inheritance of interface.
Interfaces provide a mechanism for your classes to share characteristics. Interfaces are used most often when you want to assign behavior to classes that do not all descend from the same superclass, and when this behavior needs to be redefined for each object that implements a particular interface.
You define an interface similarly to how you define a class. However, all variables in an interface are class variables and constants, and all methods are abstract. Here's an example from the subatomic world (for more information on subatomics, check out this link to Fermi Labs

Arrays of type interface, abstract class, and class Object

The type of an array can also be an interface or an abstract class. What values do elements of these arrays store?
Let us take a look at some examples.

Interface Type

If the type of an array is an interface, its elements are either null or objects that implement the relevant interface type. For example, for the interface MyInterface, the array interfaceArray can store references to objects of either the class MyClass1 or MyClass2:
interface MyInterface {}
class MyClass1 implements MyInterface {}
class MyClass2 implements MyInterface {}
class Test {
  MyInterface[] interfaceArray = new MyInterface[]{
    new MyClass1(),
    null,
    new MyClass2()
  };
}

interface ElectricallyCharged {
  int units = 3; // electric charge is charge()/units
  int charge();
}
// ----- TopQuark
class TopQuark implements ElectricallyCharged {
 public int charge() {
 return 2;
 }
}

Notice that charge() is defined as public in the class definition for TopQuark. This is because methods are implicitly defined as public in an interface.
Just as we've done for TopQuark, we could make other particles electrically charged by indicating that they immplement this interface.

Implementing Interface - Exercise

To play around with this concept of interfaces, complete an exercise that asks you to implement one of Java's interfaces.
Implementing Interface - Exercise

Java Interfaces - Quiz

The following quiz asks a few questions about interfaces.
Java Interfaces - Quiz