Java programming course: 4.6 Interfaces

In the previous lesson we wrote a class to model a zoo visitor.


Interfaces

A Java interface (not to be confused with a user interface) is like a class in that it defines a named type that has a group of related method specifications. In an interface, however, there are no method bodies, that is, there is no code provided for the methods and there are no instance variables.

Interfaces are used to provide a reusable type that formalises what an object can do. They are also a means of overcoming the restrictions of Java of only being able to extend one class (through inheritance), since a class may implement any number of interfaces.

In your zoo application, the administrator envisages sending out email newsletters to both zookeepers and visitors. The pertinent information needed in order to send out the email is simply the email address. Both the ZooKeeper class and the Visitor class have an email attribute, but the classes are independent.

You will now define a ZooAdministrator class in virtualzoo.core with a method called sendEmail() which takes a ZooKeeper object as its argument:

package virtualzoo.core;

public class ZooAdministrator {
    
   public void sendEmail(ZooKeeper zooKeeper) {
      System.out.println("Sending email to " + zooKeeper.getEmail());
   }
    
}
 

Note that you won't write any code to send emails, but just send some text to the Output window to simulate the process.

There is an optional additional download called JavaMail that can be used for email management, but this is beyond the scope of this course
// Create a zoo keeper
ZooKeeper alice = new ZooKeeper("Alice Smith", "Some City",
                "", new BigDecimal("20000"));
        
// Get the administrator to send an email to Alice
admin.sendEmail(alice);
 

Now suppose you have a visitor to whom an email should also be sent:

// Create a visitor
Visitor mary = new Visitor("Mary", "");
        
// Try to send Mary an email
admin.sendEmail(mary); // WON'T COMPILE
 

Java will not compile the class since the sendEmail() method only allows objects of type ZooKeeper to be passed as the argument. One solution would be to overload the sendEmail() method in ZooAdministrator, as follows:

public class ZooAdministrator {
    
   public void sendEmail(ZooKeeper zooKeeper) {
      System.out.println("Sending email to " + zooKeeper.getEmail());
   }
    
   // DON'T DO THIS...
   public void sendEmail(Visitor visitor) {
      System.out.println("Sending email to " + visitor.getEmail());
   }
    
}
 

The above would work but imagine that potentially there could be many otherwise unrelated classes with an email address attribute; you would have to define a new overloaded method for each class type.

A Java interface provides a neat solution to this. You can think of an interface as defining a capability (or set of capabilities) which you can add to a class's current capabilities. Using NetBeans, right-click on the virtualzoo.core package node and select New | Java Interface..., calling it Emailable:

Because interfaces are often used to add capabilities they are frequently named ending in "ible" or "able", although this is not a requirement of Java.
package virtualzoo;

public interface Emailable {
    
}
 

Note that the keyword interface is used where you have previously used class. Now enter the following method specification:

package virtualzoo.core;

public interface Emailable {
       
    public String getEmail();	// recipient's email address
    
}
 

As mentioned at the start of this section, method declarations in an interface have no bodies: they simply end in a semi-colon. To make use of the Emailable interface, modify the class declarations of both ZooKeeper and Visitor as follows:

Firstly in ZooKeeper:

public class ZooKeeper implements Emailable { 

And also in Visitor:

public class Visitor implements Emailable { 

The implements keyword means that these classes now must include the method getEmail(), as was specified in the interface. You might want to think of an interface as being a kind of "contract", that implementing classes agree to abide by. Each implementing class can implement the required method(s) however they see fit, the only requirement is that they do so in some way.

As it happens, both ZooKeeper and Visitor already have defined a method called getEmail() so no further action is needed in these classes. However, to show you how the contract holds, try removing this method – you will find that Java will no longer compile these classes since they no longer abide by the "contract".

The final step is now to modify ZooAdministrator to take advantage of the interface. You now only need one sendEmail() method, and it takes an argument of type Emailable:

public class ZooAdministrator {
    
   public void sendEmail(Emailable emailable) {
      System.out.println("Sending email to " + emailable.getEmail());
   }
    
}
 

The VirtualZoo class will now send the email to both Alice and Mary, even though one is a zookeeper and the other is a visitor. They are, however, now both Emailable.

Despite the apparent simplicity of interfaces, they are in fact a very powerful feature of Java, especially when you consider that a single class may implement any number of them. You will see this done in a later section.


In the next lesson we will enhance ZooAdministrator to start managing the zoo.

Next lesson: 4.7 Using ZooAdministrator to manage the zoo 


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image