9. Interfaces

About this Tutorial –

Objectives –

This course is aimed at object-oriented developers (e.g. C++ or C#) who need to transition into Java. It is also aimed at those learning to program for the first time; the course covers the Java programming constructs and APIs quickly, focussing on the differences between Java and other OO languages.

Audience

This training course is aimed at OO developers who need to transition into Java.

Prerequisites

No previous experience in Java programming is required. But any experience you do have in programming will help. Also no experience in eclipse is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The Java course cover these topics and more:

  • Flow Control: Decision making: if and if-else; The switch statement; Looping: for loops; while loops; do-while loops; for-each style loops; Assertionsv
  • Concurrency: Overview of multithreading; Creating new threads; Object locking; Using wait, notify, and notifyAll
  • Collections: Overview of Java SE collection classes; Generics; Using List-based collection classes; Using Set-based collection classes; Using Map-based collection classes; Collection techniques

Exam Preparation

The Java course will help you prepare for these certifications:

  • Oracle Certified Java Associate – Exam 1Z0-803
  • Oracle Certified Java Professional – Exam 1Z0-804

Download Solutions

HTML tutorial


Overview

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Collections and Generics

Lab 1: Overview of interfaces

Lab 1: Overview of interfaces
  1. Interfaces and OO
    • Interfaces are a very important part of object-oriented development
      • Allows you to specify a group of related methods, without having to worry about how they will be implemented
      • Some other class(es) in the system will provide the implementation details
      • Allows classes from different parts of an inheritance hierarchy to exhibit common behaviour
  2. Benefits of Interfaces
    • Here are some of the potential benefits of interfaces:
      • Contract-based development between consumer and supplier of functionality
      • Decoupling between subsystems
      • Flexibility, because you can plug in different implementations later without breaking the client
      • Specify the “what”, not the “how”
  3. Interfaces and Implementation Classes
    • An interface can specify method signatures and constants
      • Use the interface keyword to define the interface
        interface nameOfInterface {
         method signatures
         constants
        }
    • A class can implement any number of interface
      • Use the implements keyword, followed by a comma-separated list of interfaces you want to implement
      • The class must implement all methods defined in the interfaces
      • The class can use the constants defined in the interface
        public class nameOfClass implements interface1, interface2, ...{
         ...
         implementation of all the methods defined in the interfaces
         ...
        }
  4. Rules for Interfaces and Impl. Classes
    • Interfaces cannot contain any implementation code
      • They are purely a contract (between consumer and the implementation class)
    • Interfaces can inherit from other interfaces
      • To create a layered hierarchy of interfaces
      • Multiple inheritance of interfaces is allowed!
    • If an implementation class forgets to implement any methods in the interface, you’ll get a compiler error
      • To fix, either add missing methods to the class, or declare the class as abstract
  5. Interfaces in Java SE
    • Java SE defines hundreds of standard interfaces
      • Some interfaces specify common functionality implemented by various existing classes in the Java SE library
      • Some interfaces specify methods you can implement in your own classes, to be able to plug your classes into the Java SE framework
    • Some example Java SE interfaces:
      • java.lang.Runnable – Implement this interface if you want a class to be runnable in a separate thread
      • java.io.Serializable – Implement this interface to tell the JVM it’s allowed to serialize class instances
      • java.io.Collection – Specifies functionality provided by collection classes in Java SE
      • java.io.List – Extends java.io.Collection, adds ordered-collection functionality
Lab
  1. Defining an interface
    • Open your student project and take a quick look at the code we’ve provided as the starting point for this lab. This is the sample solution from the “Inheritance” lab
    • Now define a new interface named Reservable, which represents “reservable capability”. The Reservable interface should have the following methods:
      • isReserved() – Takes no parameters, and returns a boolean to indicate whether this item is currently reserved.
      • canBeReservedFor() – Takes a Member object as a parameter, and returns a boolean to indicate whether the member is allowed to reserve this item.
      • reserveItemFor() – Takes a Member object as a parameter, and returns a boolean to indicate whether the reservation succeeded.
        public interface Reservable {
         public boolean isReserved();
         public boolean canBeReservedFor(Member member);
         public boolean reserveItemFor(Member member);
        }
      • View code file.

Lab 2: Defining and implementing interfaces

Lab 2: Defining and implementing interfaces
  1. Syntax for Defining Interfaces
    • An interface can specify method signatures and constants
      • Use the interface keyword to define the interface
      • Optionally, use the public access modifier if you want the interface to be accessible in other packages
        [public] interface nameOfInterface {
         method signatures
         constants
        }
  2. Defining Methods in an Interface
    • An interface can specify any number of methods (including zero!)
      • All methods are implicitly public and abstract
      • The public and abstract keywords on methods are optional
    • Example:
      public interface Freezable {
       void freeze();
       void unfreeze();
      }
    • View code file.
    • Note: Interface methods must not be:
      • private or protected
      • static, final, native, or strictfp
  3. Defining Constants in an Interface
    • An interface can specify any number of constants
      • All constants are implicitly public static final
      • These keywords on constants are optional
    • Example:
      public interface Loggable {
       PrintStream OUTPUT_STREAM = System.out;
       void logBrief();
       void logVerbose();
      }
    • View code file.
    • Note: Interface constants must not be:
      • private or protected
  4. Syntax for Implementing Interfaces
    • A class can implement any number of interfaces
      • Use the implements keyword, followed by a comma-separated list of interfaces you want to implement
      • The class must implement all methods defined in the interfaces
      • The class can use the constants defined in the interface
        public class nameOfClass implements interface1, interface2, ...{
         ...
         implementation of all the methods defined in the interfaces
         ...
        }
    • Note:
      • A class can extend one class, as well as implementing interfaces
        public class nameOfClass extends superclass implements interface1, interface2, ...{
         ...
        }
  5. Example Implementation Class
    • Here’s an example of a class that implements 2 interfaces
      • Freezable and Loggable
        public class Calculator implements Freezable, Loggable {
         // Implementation of Freezable.
         public void freeze()  { ...}
         public void unfreeze() { ...}
         // Implementation of Loggable.
         public void logBrief()  { ...}
         public void logVerbose() { ...}
         // Plus other members, as for a normal class
         ...
        }
      • View code file.
  6. Aside: Marker Interfaces
    • You can define an interface with no methods
      • These are called “marker interfaces
    • Here are some examples in the Java SE library:
      public interface Cloneable {}
      public interface Serializable {}
    • If a class implements these interfaces, it’s like “setting a flag”
      • If a class implements Cloneable, it indicates to the JVM that client code is allowed to call Clone() on instances
      • If a class implements Serializable, it indicates to the JVM that it’s OK to serialize instances

Interface

Lab
  1. Implementing an interface
    • In the library system, not all books will be reservable. Popular books (such as those by bestselling authors) will be reservable because they are likely to be in high demand, but many books don’t warrant this administrative overhead
    • With this in mind, define a new class named ReservableBook, to represent books which are reservable. ReservableBook must extend Book and implement the Reservable interface
      public class ReservableBook
       extends Book
       implements Reservable {
       ... }
    • View code file.
    • The ReservableBook class should have the following additional members, to extend the capabilities of the Book class:
      • An instance variable indicating the member who has reserved the book (only one reservation is allowed at a time for books)
         // Instance variables.
         private Member reserver;
      • View code file.
      • Suitable constructor(s)
         // Constructor.
         public ReservableBook(String title, String author, String isbn, Genre genre) {
          super(title, author, isbn, genre);
         }
      • View code file.
      • An implementation of isReserved(), which returns a boolean to indicate whether there is a reserver already for this item
         // Implementation of Reservable interface.
         public boolean isReserved() {
          return (reserver != null);
         }
      • View code file.
      • An implementation of canBeReservedFor(), which allows a reservation if:
        • The member passes the basic rules for borrowing a book (as specified in the canBeBorrowedBy() method)
           public boolean canBeReservedFor(Member member) {
            return canBeBorrowedBy(member);
           }
        • View code file.
      • An implementation of reserveItemFor(), as follows:
        • If the book is currently borrowed by someone, is not currently reserved, and can be reserved by this member, reserve it and return true
           public boolean reserveItemFor(Member member) {
            // Is the item currently borrowed (and not already reserved), and is the specified member allowed to reserve it?
            if (isBorrowed() && !isReserved() && canBeReservedFor(member)) {
             reserver = member;
             return true;
          }
        • View code file.
        • Otherwise, just return false.
          else {
             return false;
            }
        • View code file.
      • An override for the returnItem() method:
        • First, invoke superclass behaviour for this method, to perform the “normal” business rules for a returned item
           @Override
           public void returnItem() {
            
            // Perform the "normal" business rules for a returned item.
            super.returnItem();
        • View code file.
        • Then add some new code to test if the book is currently reserved by a member. If it is, immediately instigate a “borrow” operation for that member. In other words, as soon as a reserved book is returned, the reserver automatically becomes the new borrower. (Don’t forget to set the “reserver” instance variable to null afterwards)
            // If this item is currently reserved by a member, immediately instigate a "borrow" operation for that member.
            if (reserver != null) {
             this.borrowItemBy(reserver);
             reserver = null;
            }
           }
        • View code file.

Lab 3: Using interfaces in the client

Lab 3: Using interfaces in the client
  1. Using Interfaces for Generality
    • One of the main uses of interfaces is to make your code as general-purpose as possible
    • E.g. this method only takes ArrayList objects
      public void myMethod(ArrayList coll) ...
    • This method is more general, it takes any kind of List
      public void myMethod(List coll) ...
    • What about this method?
      public void myMethod(Collection coll) ...
  2. Using Interfaces for Flexibility
    • Imagine you’re defining a class that needs to store a reference to another class instance
      • For example, a Person has a reference to a licensed vehicle (such as a Car, Boat, Helicopter, BatMobile, etc)
    • Further imagine there is no direct inheritance relationship between all these vehicles
      • Because there’s no common functionality
    • Questions:
      • What problems does this scenario pose?
      • How do you resolve these problems?
  3. Using Interfaces in Collections
    • You can’t create instances of an interface
      • Interfaces are like extremely abstract classes
    • But it’s still allowable to declare interface variables, and to use interfaces in generic collection / array declarations
      • The interface variable can point to any object that implements the interface
        Loggable aLoggableThing;
        ArrayList loggableThings = new ArrayList();
        Loggable[] someMoreLoggableThings = new Loggable[10];
  4. Testing if an Object Implements an I/F
    • Consider the following method:
      void myMethod(Loggable obj) { ... }

      • All the compiler knows about the incoming object is that it implements a particular interface
      • The compiler doesn’t know the actual type of the object (or what other interfaces it might support)
    • If you’d like to invoke some extra functionality on the object (as specified in a separate interface), do this:
      public void demoCrossCasting(Loggable obj) {
       if (obj instanceof Freezable) {
        Freezable temp = (Freezable) obj;
        temp.freeze();
        // ...
        temp.unfreeze();
       }
      }
    • View code file.
Lab
  1. Writing client code
    • Open MainProgram.java, and uncomment the existing code. Then add some new code to test the reservation service
    • Suggestions and requirements:
      • Create a Reservable[] array, and populate it with all the reservable items (i.e. loop through the items and use instanceof to see if an item implements the Reservable interface. If it does, store a reference to the item in the Reservable[] array).
          // Create an array to hold any items that are reservable.
          Reservable[] reservableItems = new Reservable[items.length];
          
          // Populate Reservable array with all the items that are reservable.
          int pos = 0;
          for (Item item: items) {
           if (item instanceof Reservable) {
            reservableItems[pos++] = (Reservable)item;
           }
          }
      • View code file.
      • Test whether you can reserve a ReservableBook that isn’t yet borrowed. This should not be allowed.
          // Test 1: Try to reserve a ReservableBook that isn't yet borrowed. Should fail.
          boolean result1 = reservableItems[0].reserveItemFor(member1);
          System.out.println("Can we reserve a ReservableBook that isn't yet borrowed? " + result1);
      • View code file.
      • Test whether you can reserve a ReservableBook that has already been borrowed. This should succeed. Furthermore, when the book is eventually returned, it should be automatically borrowed by the member who reserved it.
          // Test 2: Try to reserve a ReservableBook that has been borrowed. Should succeed.
          items[0].borrowItemBy(member1);
          System.out.println("\nJust borrowed item: " + items[0]);
          boolean result2 = reservableItems[0].reserveItemFor(member2);
          System.out.println("Can we reserve a ReservableBook that has been borrowed? " + result2);
          items[0].returnItem();
          System.out.println("\nJust returned item: " + items[0]);
          items[0].returnItem();
          System.out.println("\nJust returned item again: " + items[0]);
      • View code file.

 

Well done. You have completed the tutorial in the Java course. The next tutorial is

10. Collections and Generics


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top