CSS font stacks & developer FAQs with Web standards

WestNIC provides reliable web hosting services

Fastwebhost offers cheap web hosting & reseller hosting services

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.

What if you were One Percent Better with Java interfaces? Java interface design FAQ ebook for iPad, Kindle, Nook and Sony Reader

Interface concepts

Q: Why use interfaces to develop Java applications?

A: It is advisable to design relatively large applications using interfaces because it makes the whole system easier to modify, extend and integrate new features. To start with you may only have one implementation of a given interface, but if you find you need slightly different behaviour in special circumstances, you only need write a class that conforms to one of the existing interfaces and it will drop in place without major modifications.

Interfaces also allow you to adapt a class from a different hierarchy to work in an existing application. The class only needs to declare it implements the interface, provide the necessary methods and it can be integrated directly as if it were created for the job.

Q: I still don't get why I should use interfaces!

A: When you first start working with Java interfaces it may seem like extra work without much pay-back, you have to write an “empty” interface definition and also write concrete methods to implement them. There is no great advantage when you are working with relatively small scale, stand-alone applications for a single purpose.

Most people first recognise the need for interfaces when they work with Java API packages that require interface implementations to work effectively, particularly the old-style Abstract Windowing Toolkit (AWT), Swing and Java threads. With Swing you must implement the ActionListener interface to respond to button clicks, for example. The more you implement Java API interfaces for specific purposes the more you will recognise when interfaces are appropriate in your own applications and start to appreciate the benefits.

AWT and Swing are strong examples of Java interface use because Graphical User Interface (GUI) classes can implement listener interfaces to handle their own click or status events. In this case, the use of an interface means no extra class definition.

public class ListeningFrameExample extends JFrame implements WindowListener {

  // Application methods

  // Example WindowListener method
  public void windowIconified(WindowEvent e) {

    // Handle window minimised events
  }

  // Other WindowListener methods
}
      

AWT and Swing event handler interfaces like ActionListener only have one method, so can easily be implemented by anonymous inline class definitions, split over several lines in the example below.

JButton button = new JButton("Example Button");

button.addActionListener(
  new ActionListener() {
    actionPerformed(ActionEvent ae) {

      // Handle the action
    }
  }
);
      

The anonymous class is instantiated using the new keyword followed by the name of the interface with parentheses, as if the interface name is the name of a concrete class. The declaration of the single actionPerformed() method follows, enclosed in curly braces. The close parenthesis on the last line is paired with the opening parenthesis of the addActionListener() method call on the first line; it encloses the whole anonymous class definition and must be followed by a semi-colon.

Q: What is the difference between interfaces and inheritance?

A: Interfaces and inheritance are closely related in Java. In short, when a class implements an interface it inherits the essential behavioural characteristics of the interface. An instance of the class can be treated the same as any other class that implements the interface. In this case, the implements keyword creates the inheritance relationship between an interface and a class.

The interface is a largely abstract model, it defines what is required to be a class of that type in terms of the methods it must provide. A class does not inherit any specific behaviour from an interface, a programmer is free to implement interface methods as they choose. So long as they match the interface method signatures a class inherits the ability to “act as” or “behave like” any other implementation class.

Interface inheritance creates polymorphism because any class that implements an interface can be cast to that type and used interchangeably with any other in variables and method arguments.

Q: But interfaces are implemented by classes, why bother?

A: When you compare interfaces with standard class hierarchies there are obvious similarities, especially compared with an entirely abstract class. Both interfaces and abstract classes can be extended and extra abstract methods added. The nature of inheritance means that sub-classes and sub-interfaces are type-compatible with their parents.

The use of interfaces in Java is partly a design compromise to support a limited form of multiple inheritance. Purely abstract interfaces enable classes to implement multiple interfaces and extend a superclass within the general constraints of the Java language and runtime environment.

The separation of interfaces from classes means it is also possible to compose Java types that are loosely coupled or entirely detached from class hierarchies, which makes them flexible to change. For example, a class may implement the java.util.List interface by encapsulating and adapting a Vector, to make a thin “wrapper” around the Vector without extending the class. At a later date you can switch the encapsulated Vector to an ArrayList, LinkedList or some other custom implementation without affecting clients of the class.

Q: How come methods in interfaces are not defined?

A: An interface represents a Java type, a concept of a set of Java classes that behave in a particular way such that any one could be used in place of another. It may help to think of a Java interface as a blueprint, plan or model that says, “write a class that has these methods.”

An interface describes what a Java class must do, but doesn't say how it should be done, that's why interface methods have no code body. A Java programmer is free to code an interface however they choose, so long as their methods have the same names, arguments and return types as the interface. That flexibility enables programmers to write or adapt many different classes to fulfil a particular interface.

Q: What is the difference between abstract classes and interfaces?

A: A Java interface is a definition of a class type without any concrete implementation. Typically, an interface consists of one or more method signatures that a subclass must fulfil to conform to the type. All their methods are abstract and interfaces cannot be instantiated.

… full answer hidden, click for full answers

Premium members click below for full answer
What is the difference between abstract classes and interfaces?

Q: Why use interfaces instead of abstract classes?

A: The key difference between abstract class and interface based inheritance is that concrete classes are bound to a single abstract class hierarchy, they are tightly coupled and cannot extend any other class. This makes it difficult to create general purpose component classes that can be re-used in different packages.

Interface based inheritance does not create a binding to a specific class hierarchy, so concrete classes can inherit the type characteristics of several interfaces without limiting their scope for re-use. Concrete classes can implement multiple interfaces and extend an abstract class, but it is best to minimise class inheritance as far as possible to preserve lexibility.

Q: What's the difference between an interface and an API?

A: An Application Programming Interface (API) is the collection of all the public methods and fields that belong to a set of classes, including its interface types. The API defines the way that developers can use the classes in their own Java program, just by importing the relevant classes and writing statements that instantiate the classes and call their public methods and fields.

A Java interface declares a type of Java object without a concrete implementation. Interfaces are defined in a compilation unit like a standard Java class and the methods they declare are implicitly part of an Application Programming Interface. Interfaces are used to help define generic structural components in an API, a reference type for concrete implementations, and an extension mechanism for programmers who use the API.

Q: Is an API a help document?

A: An Application Programming Interface (API) is a way to describe a collection, library or “toolkit” of Java software that can be used as part of new Java programs. The name Application Programming Interface refers to the components in a packaged collection of Java programs and the special properties and behaviour that they can provide in a Java program. The classes in the Java networking package enable programmers to get information from the Internet, for example. The publicly accessible Java classes, properties and methods in this collection are called the java.net API.

Ideally a Java software library should be distributed with a set of help documents that describe its API and explain how Java programmers should use the components in their own programs. These documents can be generated from specially formatted JavaDoc comments embedded in the code but they only describe the API, they are not the API itself.

Interface use

Q: When should I use an interface?

A: If you are not used to using interfaces in your Java programs you are most likely to recognise the need when you are refactoring an existing application to add a new feature or support a new input or output format. When you think about how to re-organise the program it may be difficult to see where to make the changes, the class hierarchy may seem tangled, or it feels like a new format doesn't fit in neatly. A strong sign that you need to introduce an interface is that you have very similar code in separate classes and you can't re-arrange the classes to inherit this behaviour from a common superclass.

When you recognise these characteristics in a system, you should list the behaviour the “problem objects” need to have so that the main path of the program can process them in the same way. Separate this “Processable” behaviour in an interface and keep the type-specific behaviour in the classes that need to be processed. Where you see duplicate code in the processable classes, move it up the hierarchy and perhaps head it with an AbstractProcessable class. That should leave the type-specific classes to implement the Processable interface, possibly extend the AbstractProcessable class, and focus the main content of the class on its core, distinct behaviour.

  • A Processable interface defines the type of things that can be processed in a particular way, a set of data that can be rendered as a Web page, for example.
  • An AbstractProcessable superclass may implement the Processble interface and provide some concrete methods for subclasses to use, such as a cleanUpData() method, for example.
  • Concrete ProcessableSpreadsheet, ProcessableDocument and ProcessableReport classes can extend the AbstractProcessable class and implement the Processable interface methods.
  • Finally, an HTMLRenderer class can define a render(Processable) method that accepts any of classes above that implement the Processable interface to generate HTML output.

The main path of your application will need to be adapted to declare and cast these objects as Processable types, but that will mean any other Processable type can more easily be added to the system in future.

Q: Where should I use interfaces in my application?

A: Partly that's a question that depends on the nature of your application, its overall structure and how it integrates with the Java API and third party libraries. Interfaces can be used in most areas of application development, so they could be used in any part of the system. The main things to look out for are cases where several different things need to be treated in a similar way, an interface can consolidate the common behaviour of a set of classes so that your application code can process them interchangably.

Q: When should I use abstract classes rather than interfaces?

A: Abstract classes are often used to provide methods that will be common to a range of similar subclasses, to avoid duplicating the same code in each case. Each subclass adds its own features on top of the common abstract methods.

… full answer hidden, click for full answers

Premium members click below for full answer
When should I use abstract classes rather than interfaces?

Q: How do we use interfaces as variables?

A: Java is a strongly typed language, which means that all variables and method arguments must be declared to be a particular type. The references assigned to variables and passed to methods must match their declared type, or be cast to them, to maintain the type safety of the system.

Java types fall into 3 categories:

  • Primitive types
    Including byte, boolean, char, int and other numerics.
  • Object types
    Including built-in API classes and programmer defined classes.
  • Interface types
    Types declared by interfaces and implemented by concrete classes.

Interfaces cannot be instantiated in their own right, but the concrete classes that implement them are type-compatible. That means that any class that implements the java.util.List interface can be assigned to a variable of that type, for example.

// List interface
// Vector implements List
List list = new Vector();
    

When an instance of a class is assigned to an interface type variable in this way, you can safely call any interface methods on the variable. This is an example of polymorphism in Java. A Vector has its own properties and methods, but when assigned to a List type variable, it is treated as a List and can be passed to other methods that require a List type argument.

Q: What are the rules for passing subclasses for method arguments?

A: It may help to discuss an example using birds: an interface called Avian, a superclass FlyingBird that implements Avian and two concrete classes: Parrot and Penguin. Parrot extends FlyingBird, so is implicitly an Avian type, but Penguin does not, it only implements Avian.

… full answer hidden, click for full answers

Premium members click below for full answer
What are the rules for passing subclasses for method arguments?

Q: Can you give an example of multiple inheritance with interfaces?

A: To illustrate multiple inheritance, consider a Bat, which is a mammal that flies. We might have two interfaces: Mammal, which has a method suckleInfant(Mammal), and Flyer, which has a method fly(). These types would be declared in interfaces, as below.

… full answer hidden, click for full answers

Premium members click below for full answer
Can you give an example of multiple inheritance with interfaces?

How to define an interface

Q: Should I use a public access modifier for interface methods?

A: Java interface methods are always implicitly public, even if they belong to nested interfaces. Non-public modifiers are not valid or necessary for interface methods, so the compiler should fail and warn you in this case. Nested interfaces may be declared protected or private, but the methods they define must still follow this rule, as summarised below.

… full answer hidden, click for full answers

Premium members click below for full answer
Should I use a public access modifier for interface methods?

Q: Non-public modifiers can be used for nested interfaces!

A: Interface methods must be public, the compiler will fail and issue a warning if interface methods are declared protected or private, even in nested interfaces. Nested interfaces themselves may be declared protected or private.

Q: Can we create a Java class inside an interface?

A: Yes, classes can be declared inside interfaces. This technique is sometimes used where the class is a constant type, return value or method argument in the interface. When a class is closely associated with the use of an interface it is convenient to declare it in the same compilation unit. This proximity also helps ensure that implementation changes to either are mutually compatible.

A class defined inside an interface is implicitly public static and operates as a top level class. The static modifier does not have the same effect on a nested class as it does with class variables and methods. The example below shows the definition of a StoreProcessor interface with nested StorageUnit class which is used in the two interface methods.

… full answer hidden, click for full answers

Premium members click below for full answer
Can we create a Java class inside an interface?

Q: Can an interface extend a class?

A: In Java an interface can only extend another interface, called a super-interface. This is an inheritance relationship like superclass-subclass; the sub-interface inherits all the constant variables and abstract methods defined in the super-interface and can add its own.

Since an interface may have a static class defined within it, it is possible for a class in a sub-interface to extend a class in a super-interface, but that is a different thing entirely. In this case the extension of nested classes is no different from standard extends inheritance except the hosts of the classes are interfaces. There is no mixture of class and interface extension.

Q: Can an interface extend an abstract class?

A: In Java an interface cannot extend an abstract class. An interface may only extend a super-interface. However, an abstract class can implement an interface. It may help to think of interfaces and classes as separate lines of inheritance that only come together when a class implements an interface, the relationship cannot be reversed.

Q: Can an interface be declared final?

A: It is not permitted to declare an interface as final, it will cause a compilation error. This is a Java language design decision. Interface types are intended to be implemented and can be extended without restriction. Some regard this free extensibility as a flaw in the language design because there are cases where it would be useful to restrict the broader use of an interface. In the current scheme it does not make sense to declare an interface final because it would imply it could not be extended and possibly not implemented, which would not be useful.

How to implement an interface

Q: Can we create an object for an interface?

A: Yes, the most common scenario is to create an object implementation for an interface, although they can be used as a pure reference type. Interfaces cannot be instantiated in their own right, so it is usual to write a class that implements the interface and fulfils the methods defined in it.

public class Concrete implements ExampleInterface {

  ...
}
      
Q: Is more than one interface allowed?

A: Yes, a class can implement multiple interfaces, this is an effective way to achieve multiple inheritance in Java. A class can only extend one superclass.

Q: Is it necessary to implement all interface methods?

A: It is not necessary for a class that implements an interface to implement all its methods, but in this case the class must be declared abstract. In this respect the implementation of an interface is similar to the extension of an abstract class. The implementation of the interface methods can be deferred through any number of abstract subclasses, but at some point you should create concrete implementations. In fact, its a sign there may be something wrong with your code design if you defer interface implementation in more than one or two subclasses.

Q: How is the implements keyword different from extends?

A: The implements keyword is used when a class explicitly fulfils an interface definition with concrete method implementations for its abstract method signatures. A single class can implement more than one interface, but must be declared abstract if it does not implement all interface methods.

The extends keyword is used when an interface inherits the type definition specified in a super-interface, or a class inherits from a superclass. A class can only extend a single superclass but may also implement one or more interfaces.

When an interface extends a super-interface it is not required or permitted to implement any of its abstract methods since the sub-interface must be abstract itself.

Q: Can you show how to implement an interface?

A: Simple examples are not always strong examples, but this case shows an AreaInterface with a single method getArea() and how that is implemented in ConcreteCircle, ConcreteSquare and ConcreteRectangle classes.

public interface AreaInterface {

  double getArea();
}
    

… full answer hidden, click for full answers

Premium members click below for full answer
Can you show how to implement an interface?

Q: This code seems to be instantiating an interface!

A: The code you are looking at declares an inline anonymous class that implements an interface, which has a similar effect. This declaration does not instantiate the interface, but defines the type of the anonymous class, which has no name of its own. This approach is often used in old-style Abstract Windowing Toolkit (AWT) or Swing applications where a class is required to fulfil a minimal interface and it is not necessary to retain a reference to it by assignment.

… full answer hidden, click for full answers

Premium members click below for full answer
This code seems to be instantiating an interface!

Q: What if two interface methods clash in implementation?

A: If two interfaces have the same method signature, they effectively declare the same method regardless of any other intentions. Any concrete class that implements both interfaces can only provide one implementation of a given method signature, so there is no ambiguity about how the Java compiler deals with this case, only a potentially difficult design decision.

If two interface methods have a clash over their method signatures and intended behaviour, it would preferable to rename one of the interface methods to indicate a more distinct purpose.

Q: When interfaces clash, which method answers the call?

A: In this case neither interface answers the method call, thus it is not a problem. The interface methods must be implemented by a concrete class and it is the single concrete method in the implementation class that will handle the call. The example below shows that the behaviour defined in the concrete method will be executed regardless of the reference type used for its instance.

… full answer hidden, click for full answers

Premium members click below for full answer
When interfaces clash, which method answers the call?

Marker interfaces

Q: What is a marker interface?

A: Marker interfaces do not declare any required methods, but their implementation signifies compatibility with certain operations. The java.io.Serializable interface is a typical marker interface, classes must implement this interface in order for their instances to be serialized and de-serialized.

Q: How do marker interfaces affect the behaviour of classes?

A: Marker interfaces do not affect the classes that implement them through their behaviour, they cannot since there are no required methods, they only mark the class by identifying it as a Java type that conforms to the interface. In the classic example, methods that serialize data can check that a class can be serialized by its implementation of the Serializable interface.

Q: Are there any marker interfaces that have methods?

A: No, the definition of a marker interface is that it contains no behavioural definitions, so there can be no marker interface that has methods. Marker interfaces are concerned with being a certain type rather than behaving as a type does.

Q: Can we implement a marker interface?

A: Yes, marker interfaces can be implemented, just add the implements keyword and the name of the interface to your class declaration, as below.

public class ExampleSerializable implements Serializable {

  // No interface methods to implement
}
    
Q: Why do we need to implement the Serializable interface?

A: In some respects marker interfaces such as Serializable are like a prompt or reminder to programmers that we must implement the interface to get the results we need; most importantly we must ensure that the class is truly serializable.

A class must implement the Serializable interface else any attempt to serialize an instance will throw a NotSerializableException. However, it is the programmer's responsibility to ensure that an instance can physically be serialized and de-serialized in a meaningful way, so that the object's original state can be fully restored. That can be a complex task, especially when a class has field types that are final and do not implement the Serializable interface, hence the interface is a marker that special measures need to be taken.

Q: Can you show an example marker interface?

A: An interface typically represents something that is “Processable” in a particular way. Marker interfaces don't have any interface methods, they usually signify a property or state that any Java class may have that cannot be defined by a method signature. An example would be an Immutable interface, since a fundamental characteristic of immutable classes is the absence of mutator methods.

… full answer hidden, click for full answers

Premium members click below for full answer
Can you show an example marker interface?

Interface constants

Q: Do interfaces have member variables?

A: Interfaces may have variable fields but they are implicitly final and static. Interface variables are inherited by any class that implements the interface and are also available as public static variables of the interface. In effect, interface variables are constants that are available to all implementations and may be used as key references for method arguments, for example.

Q: Are you sure you can declare member variables in an interface?

A: Yes, it is definitely possible to declare member variables in an interface, though it may help to call them static member variables. Interface variables are implicitly static, even if you omit the static keyword they will be compiled and treated as public static final constants. You cannot declare an instance variable in a Java interface.

Q: Why are interface variables public static final?

A: The short answer is that interface variables are intended to be Java constants, which means they must have these universal and un-changable properties. Interface variables are implicitly public because interfaces are intended to provide an Application Programming Interface (API) that is fully accessible to Java programmers to reference and implement in their own applications. Since an interface may be used in Java packages that are different from their own, public visibility ensures that program code can access the variable.

Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

Q: Interface variables can be overridden, right?

A: No, interface variables are constants that cannot be overridden. They are inherited by any class that implements an interface.

Q: This interface variable is assigned in a constructor!

A: In this case a final instance variable in a class is declared as an interface type, which is different from a constant field in an interface. The example below shows a List type assigned a final variable in a class constructor. Any object that fulfils the List interface can be passed to the class constructor and assigned to its final instance variable. The final variable cannot be changed after instantiation.

… full answer hidden, click for full answers

Premium members click below for full answer
This interface variable is assigned in a constructor!

Q: What style should I use to declare a member variable in an interface?

A: The way that interface constants are declared is arbitrary, whether you use the full public static final modifiers or none at all the compiled code will be the same. Java code style is intended to help the reader without stopping to think too hard. The convention of setting constant variable names in upper case letters with underscore separators, CONSTANT_NAME, is recommended and likely to be a stronger guide to the nature of the constant.

Q: Is this interface constant declaration correct?

A: Your interface constant declaration is wrong for two reasons. Firstly, the keyword interface cannot be used in variable declarations, only in the enclosing interface declaration itself, as below.

public interface Example {

  // API declarations
}
      

Secondly, the type of the variable must match that of the value that is assigned to it; an int cannot be assigned a String value. Standard Java code style is to give your interface constant an uppercase variable name with words separated by underscores.

public static final String EXAMPLE = "Constant example";
      
Home · Web fonts · Font stacks · FAQs · Java · CSS · Javascript · HTML · Site manager