Previous
Index

Next


Objective 2, Using interfaces

Identify classes that correctly implement an interface where that interface is either java.lang.Runnable or a fully specified interface in the question.

Interfaces -Programming by contract

Interfaces are part of what is known as “programming by contract”. This means that a programmer creates something that obliges other programmers to follow a set of conditions. Interfaces are also considered to be the way Java gains some of the benefits of multiple inheritance without the drawbacks. The C++ language has multiple inheritance, meaning a class can have more than one parent. The benefits and drawbacks of multiple versus single inheritance is the subject of much debate amongst programming theorists.

The Runnable Interface

The Runnable interface is part of the Threading mechanism which is addressed specifically in other exam objectives. The Runnable interfaces specifies that a class that implements it must define a method with the signature

public void run()

The keyword for using interfaces is implements, thus if you intend to create a class that implements the Runnable interface it will look something likely

public class MyClass implements Runnable{
    public void run(){}
}

Of course to do anything useful you need to put some code in the body of the run method, but simply creating a run method with the appropriate signature is enough to fulfill the contract required by the Runnable interface. Unless you have a method with the exactly correct signature you will get a compile time error. T

Other sources on this subject

The Sun Java Tutorial
http://java.sun.com/docs/books/tutorial/java/interpack/interfaces.html

Central Connecticut State University
http://chortle.ccsu.edu/cs151/Notes/chap53/ch53_1.html




Previous
Index

Next