Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Introduction to Java programming, Part 2: Constructs for real-world applications

More-advanced Java language features

J Steven Perry, Principal Consultant, Makoto Consulting Group, Inc.
Photo of J Steven Perry
J. Steven Perry is a software developer, architect, and general Java nut who has been developing software professionally since 1991. His professional interests range from the inner workings of the JVM to UML modeling and everything in between. Steve has a passion for writing and mentoring; he is the author of Java Management Extensions (O'Reilly), Log4j (O'Reilly), and the IBM developerWorks articles "Joda-Time" and OpenID for Java Web applications." In his spare time, he hangs out with his three kids, rides his bike, and teaches yoga.

Summary:  In Part 1 of this tutorial, professional Java™ programmer J. Steven Perry introduced the Java language syntax and libraries you need to write simple Java applications. Part 2, still geared toward developers new to Java application development, introduces the more-sophisticated programming constructs required for building complex, real-world Java applications. Topics covered include exception handling, inheritance and abstraction, regular expressions, generics, Java I/O, and Java serialization.

View more content in this series

Date:  19 Aug 2010
Level:  Introductory PDF:  A4 and Letter (904 KB | 53 pages)Get Adobe® Reader®



In this section, begin learning about interfaces and start using them in your Java code.

Defining an interface

An interface is a named set of behaviors (and/or constant data elements) for which an implementer must provide code. An interface specifies what behavior the implementation provides, but not how it is accomplished.

Defining an interface is straightforward:

public interface  interfaceName {
 returnType methodName( argumentList );

An interface declaration looks like a class declaration, except that you use the interface keyword. You can name the interface anything you want to (subject to language rules), but by convention interface names look like class names.

Methods defined in an interface have no method body. The implementer of the interface is responsible for providing the method body (just as with abstract methods).

You define hierarchies of interfaces, just as you do for classes, except that a single class can implement as many interfaces as it wants to. (Remember, a class can extend only one class.) If one class extends another and implements interface(s), then the interfaces are listed after the extended class, like this:

public class Manager extends Employee implements BonusEligible, StockOptionRecipient {
// Etc...

Marker interfaces

An interface does not need to have any body at all. In fact, the following definition is perfectly acceptable:

public interface BonusEligible {

Generally speaking, such interfaces are called marker interfaces, because they mark a class as implementing that interface but offer no special explicit behavior.

Once you know all that, actually defining an interface is easy:

public interface StockOptionRecipient {
 void processStockOptions(int numberOfOptions, BigDecimal price);

Implementing interfaces

To use an interface, you implement it, which simply means providing a method body, which in turn provides the behavior to fulfill the interface's contract. You do that with the implements keyword:

public class className extends superclassName implements interfaceName {
// Class Body

Suppose you implement the StockOptionRecipient interface on the Manager class, as shown in Listing 15:

Listing 15. Implementing an interface

public class Manager extends Employee implements StockOptionRecipient {
 public Manager() {
 public void processStockOptions (int numberOfOptions, BigDecimal price) {"I can't believe I got " + number + " options at $" + 
            price.toPlainString() + "!");  }

When you implement the interface, you provide behavior for the method(s) on the interface. You must implement the methods with signatures that match the ones on the interface, with the addition of the public access modifier.

Generating interfaces in Eclipse

Eclipse can easily generate the correct method signature for you if you decide one of your classes should implement an interface. Just change the class signature to implement the interface. Eclipse puts a red squiggly line under the class, flagging it to be in error because the class doesn't provide the method(s) on the interface. Click the class name with your mouse, press Ctrl + 1, and Eclipse will suggest "quick fixes" for you. Of these, choose Add Unimplemented Methods, and Eclipse will generate the methods for you, placing them at the bottom of the source file.

An abstract class can declare that it implements a particular interface, but it isn't required to implement all of the methods on that interface. This is because abstract classes aren't required to provide implementations for all of the methods they claim to implement. However, the first concrete class (that is, the first one that can be instantiated) must implement all methods the hierarchy does not.

Using interfaces

An interface defines a new reference data type, which means you can refer to an interface anywhere you would refer to a class. This includes when you declare a reference variable, or cast from one type to another, as shown in Listing 16.

Listing 16. Assigning a new Manager instance to a StockOptionEligible reference

public static void main(String[] args) {
 StockOptionEligible soe = new Manager();// perfectly valid
 calculateAndAwardStockOptions(new Manager());// works too
. . .
public static void calculateAndAwardStockOptions(StockOptionEligible soe) {
 BigDecimal reallyCheapPrice = BigDecimal.valueOf(0.01);
 int numberOfOptions = 10000;
 soe.processStockOptions(numberOfOptions, reallyCheapPrice);

As you can see, it is perfectly valid to assign a new Manager instance to a StockOptionEligible reference, as well as to pass a new Manager instance to a method that expects a StockOptionEligible reference.

Assignments: Classes

When assigning a reference from a class that implements an interface to a variable of an interface type, you can do so, but there are rules. From Listing 16, we see that assigning a Manager instance to a StockOptionEligible variable reference is perfectly valid. The reason is that the Manager class implements that interface. However, the following assignment would not be valid:

  Manager m = new Manager();
  StockOptionEligible soe = m; //okay
  Employee e = soe; // Wrong!

Because Employee is supertype of Manager, this might at first seem okay, but it is not. Because Manager is a specialization of Employee, it is *different* and in this particular case implements an interface that Employee does not.

Assignments such as these follow the rules of assignment we saw in Inheritance. And just like with classes, you may only assign an interface reference to a variable of the same type or a superinterface type.

6 of 14 | Previous | Next


Zone=Java technology
TutorialTitle=Introduction to Java programming, Part 2: Constructs for real-world applications