Example interface

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

Object

Example interface

Here is an example interface definition. The constants don't have to be separated from the methods, but doing so makes the interface easier to read.

interface MyInterface
{
  public static final int aConstant = 32;     // a constant
  public static final double pi = 3.14159;    // a constant

  public void methodA( int x );               // a method declaration
  public double methodB();                    // a method declaration
}

A method in an interface cannot be made private. A method in an interface is public by default. The constants in an interface are public static final by default. Making use of the defaults, the above interface is equivalent to the following:

interface MyInterface
{
  int aConstant = 32;     // a constant
  double pi = 3.14159;    // a constant

  void methodA( int x );  // a method declaration
  double methodB();       // a method declaration
}

The second interface (above) is the preferred way to define an interface. The defaults are assumed and not explicitly coded.

  • A class that implements an interface must implement each method in the interface.
  • Methods from the interface must be declared public in the class.
  • Constants from the interface can be used as if they had been defined in the class.
  • Constants should not be redefined in the class.

QUESTION 4:

interface SomeInterface
{
  public final int x = 32;
  public double y;

  public double addup( );
}

Inspect the interface. Is it correct? Click here for a