Creating an Interface Definition

Contact Us or call 1-877-932-8228
Creating an Interface Definition

Creating an Interface Definition

To create an interface definition:

  • Define it like a Java class, in its own file that matches the interface name.
  • Use the keyword interface instead of class.
  • Declare methods using the same approach as abstract methods.
    • Note the semicolon after each method declaration - and that no executable code is supplied (and no curly braces).
    • The elements will automatically be public and abstract, and cannot have any other state; it is OK to specify those terms, but not necessary (usually public is specified and abstract is not - that makes it easy to copy the list of methods, paste them into a class, and modify them).
  • The access level for the entire interface is usually public.
    • It may be omitted, in which case the interface is only available to other classes in the same package (i.e., in the same directory).
    • Note, for the sake of completeness, there are situations where the interface definition could be protected or private; these involve what are called inner classes.
[modifiers] interface InterfaceName {

	// declaring methods
	[public abstract] returnType methodName1(arguments);

	// defining constants
	[public static final] type fieldName = value;
}

Code Sample:

Java-Interfaces/Demos/Printable.java
public interface Printable {
  void printAll();
}

This interface requires only one method. Any class implementing Printable must contain a public void printall() method in order to compile.

Because the above interface is defined as public, its definition must be in its own file, even though that file will be tiny.

An interface definition may also define fields that are automatically public static final - these are used as constants.

Next