CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Interfaces

Interfaces
Interfaces
Code

How to code an interface

  • Declaring an interface is similar to declaring a class except that you use the interface keyword instead of the class keyword.
  • In an interface, all methods are automatically declared public and abstract, and all constants are automatically declared public, static, and final, so the access modifiers are optional.
  • Interface methods can't be static.

The syntax for declaring an interface

public interface InterfaceName
{
    type CONSTANT_NAME = value;               // declares a field
    returnType methodName([parameterList]);   // declares a method
}

An interface that defines one method

public interface Printable
{
    void print();
}

An interface that defines three methods

public interface ProductWriter
{
    boolean addProduct(Product p);
    boolean updateProduct(Product p);
    boolean deleteProduct(Product p);
}

An interface that defines constants

public interface DepartmentConstants
{
    int ADMIN = 1;
    int EDITORIAL = 2;
    int MARKETING = 3;
}

A tagging interface with no members

public interface Cloneable
{
}
Previous | Code | Implement | Inherit a class | Use an interface as a parameter | Use inheritance with interfaces | Next