How to work with interfaces

The syntax for declaring an interface

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

  • interfaces can not contain code
  • all methods are automaticly declared as public, abstrace.
  • all fields are automaticly declared public, static, and final.
  • interface methods can't be static.

An example of an interface:

public interface Products
{
int ADMIN = 1;
int USER = 2;
bollean addProduct(Product product);
bollean deleteProduct(Product product);
}

How to implement and interface

public class MyProducts implements Products
{
bollean addProduct(Product product)
{
if (user != ADMIN )
… code goes here
}
bollean deleteProduct(Product product)
{
… code goes here
}
}

How to inherit a class and implement an interface

public class SubclassName extends SuperClassName implements Interface1[, interface2] { }