Monday, July 7, 2008

Java JEE5 Job Interview Questions: Java Interfaces

What is a Java interface? What is the purpose of a Java interface?

An interface is a special Java type that allows an application designer to express commonality across classes that might not have a common inheritance hierarchy. Essentially, an interface provides a mechanism for expressing an is-a type of relationship between classes, while at the same time, avoiding many of the problems associated with multiple inheritance.

For example, a bird, a helicopter and paper airplane all fly. However, each one of these flies in a uniquely characteristic way. A bird, helicopter and a paper airplane would not likely share a common inheritance hierarchy in a hypothetical application design. However, they could all implement a common Flyable interface, and as such, we could express the commonality between a bird, helicopter and a paper airplane, in so much as all of these items fly.

How do you define a Java interface?

A Java interface is defined by using an access modifier, the keyword interface, all followed by the name of the interface.

An interface can only declare abstract methods and constants (that is, static final properties.) This forces implementing classes to define their implementation of the interface methods in their own unique way, so with our Flyable example, a bird, a helicopter and a paper airplane would all have their own, unique implementation of methods such as takeOff() and land(). However, despite the different method implementations in the implementing concrete classes, the fact that the classes all implement the same interface demonstrates commonality.

public interface Flyable {

public static final double GRAVITY = 9.8;

public abstract void takeOff();
public abstract void land();

}

I hope this helps answer the following questions I commonly get: What is the point of Java interfaces? Java interfaces are useless? Why do we need interfaces in Java? I don't get Java interfaces? What are Java interfaces? How are Java interfaces useful?

What is a marker interface?

A marker is an interface that does not define any methods whatsoever.

The java.io.Serializable interface is a marker interface, as it does not define any abstract methods. However, it is very useful to implement this interface, as it expresses a contract between the developer and the system that commits to ensuring that the class itself will be capable of capturing its internal state and make it transportable across a network or to the file system.

No comments: