Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Language Fundamentals - Interface Declarations

Syntax (JJ pg142)

        modifiers interface InterfaceName extendsClause {
            // Interface body
         }

The modifiers and extendsClause are optional.

A compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces (JLS §9.1)

Modifiers (JLS §9.1.1)

    public protected private
    abstract static strictfp
Note
  • top-level interfaces may only be declared public
    private interface A {}          // compile error
    protected interface B{}         // compile error
  • inner interfaces may be declared private and protected BUT only if they are defined in a class
    public interface A {
        private interface B {}          // compile error
        protected interface C {}        // compile error
    }
    
    public class A {
        private interface B {}          // compiles OK
        protected interface C {}        // compile OK
    
    }
    
  • a compile error occurs if the same modifier appears more than once in an interface declaration (JLS §9.1.1)
  • every interface is implicitly abstract; the modifier is obsolete and should not be used in new programs (JLS §9.1.1.1)

extendsClause

  • consists of the extends keyword followed by a comma separated list of the interfaces being extended.
Note
  • Classes are based on single-inheritance, they can only extend one class.
  • Interfaces are allowed multiple-inheritance, they can extend more than one interface.
        interface InterfaceA extends
          interfaceX, interfaceY, ... {}

Interface body

  • an interface body may contain constant declarations, abstract method declarations, inner classes and inner interfaces
  • fields in an interface are implicitly static and final ie they MUST be constants (JLS§9.3)
  • methods in an interface are implicitly abstract and public; they CANNOT be static (JLS§9.4)
  • methods cannot be declared strictfp, native or synchronized (JLS§9.4)
  • member classes declared in an interface are implicitly public and static (JLS§9.5)

Also see

Code Examples

Traps

  • an interface method declared as native or synchronized
  • an interface method declared as static


Source Package Import Class Interface Constructors
  Methods main() Identifiers Keywords Defaults Arrays
  Primitives # Literals char Literal String Literals Class Literals