Java Java intro
  1. Java intro
  2. Java basics
Java core
  1. Java variables
  2. Java conditionals
  3. Java loops
  4. Java arrays
  5. Java strings
Object-oriented Java
  1. Java OOP 1
  2. Java OOP 2
  3. Java packages
  4. Java interfaces
Java interactive
  1. Java user input
  2. Java exceptions
  3. Java events
Graphical Java
  1. Java GUI
  2. Java GUI layout
  3. Java graphics
Java extras
  1. Java applets
  2. Java sounds
  3. Java random numbers
Java wrap-up
  1. Java summary

Java interfaces

An interface is a collection of methods that have no implementation - they are just created, but have no functionality. What's the purpose of such methods? For you to define their functionality individually in different classes. An interface is abstract, and you define how it's elements (methods) work according to your needs.

This tutorial focuses on:

Different Java interfaces

Java provides many different interfaces for a wide variety of functionality.

Declaring an interface

While Java provides interfaces for you to use, you can also create your own.

An interface is declared with the interface keyword.

interface nameOfInterface{ //methods for interface here; }
interface DataManager{ }

You can add methods to an interface the same way you would add methods to a class, except the methods in an interface have no implementation.

Adding methods to an interface:
interface DataManager{ public void printData(String data); public String getUserInput(); }

Just like regular Java programs, interfaces should be declared in separate files, the name of the file an interface is declared in should have the same name as the interface (including the same capitalization), and should have a .java extension. For example, the code for the interface from above should be in a separate file named

Using an interface

To use an interface, use the implements keyword with the name of the interface in the class declaration line in your code. You specify that a class implements the interface and you define in that class what the methods from the interface do.

class nameOfClass implements nameOfInterface{ }
class ClassOne implements DataManager{ }

The ClassOne class can now use the methods declared in the DataManager interface and define their functionality.

NOTE: Remember to always import the package that contains the interface you are implementing like in the example below.

import java.awt.event.*; class FrameWithEvents implements WindowListener{ }
© Copyright 2013-2014
Terms of use | Privacy policy | Copyright information