Java
Java intro
Java basics
Java variables
Java conditionals
Java loops
Java arrays
Java OOP 1
Java OOP 2
Java interfaces
Java Strings
Java user input
Java exceptions
Java packages
Java rand numbers
Java GUI's
Java GUI layout
Java events
Java applets
Java graphics
Java sounds
Java summary

Programming

Programming intro

Markup

First webpage guide HTML
XHTML

Style & Layout

CSS

Browser scripting

Javascript
VBScript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

Java interfaces

An interface is a collection of methods that have no implementation but can be used by classes and the implementation of these methods is defined individually by classes.

This lesson focuses on:

Declaring an interface

An interface is declared with the interface keyword.

Syntax:

interface nameOfInterface{

}

Example:

interface anInterface{

}

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.

Example:

interface anInterface{

public void printData(String data);

public String getUserInput();

}

In the above example, an interface named anInterface is declared with the method printData(String data) and getUserInput().

NOTE: Interfaces should be declared in separate files, and 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 anInterface.java

Using an interface

To use an interface use the implements keyword with the name of the interface in a class definition.

Syntax:

class nameOfClass implements nameOfInterface{

}

Example:

class AClass implements anInterface{

}

In the above example, a class named AClass calls the anInterface interface. The aClass class can now use the methods declared in the anInterface interface and define their implementation.

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments