Interfaces and Inheritance

Contact Us or call 1-877-932-8228
Interfaces and Inheritance

Interfaces and Inheritance

If a class implements an interface, then all subclasses of it will also automatically implement the interface.

  • They are guaranteed to have the necessary methods available.
  • It is a good practice to specify that the derived class implements the interface, just for self-documentation of the code (also for purposes of javadoc, if the base class is not in the same group of files).

An interface definition can inherit from another interface.

  • The new interface then adds fields and methods to the existing (base) definition.
  • A class that implements the new interface must implement all methods from the base interface as well as all the additional methods from the new interface definition.
  • An interface can actually extend multiple base interfaces, in which case the combination of all the methods will be required for any implementing class.

The following interface extends the Printable interface and adds another required method (the new method overloads printAll to print to a specified destination instead of to System.out):

Code Sample:

Java-Interfaces/Demos/Printable2.java
import java.io.PrintStream;
public interface Printable2 extends Printable {
  public void printAll(PrintStream p);
}

A class implementing Printable2 must define both versions of printAll.

Code Sample:

Java-Interfaces/Demos/Printable2Test.java
import java.io.PrintStream;
class Cat implements Printable2 {
  public void printAll() {
    printAll(System.out);
  }
  public void printAll(PrintStream out) {
    out.println("Meow");
  }
}

public class Printable2Test {
  public static void main(String[] args) {
    Printable2 c = new Cat();
    c.printAll(System.err);
    c.printAll();
  }
}

Solution:

Solutions/Payroll-Interfaces01/Payroll.java
import employees.*;
import vendors.Invoice;
import finance.*;
import util.*;

public class Payroll {	
	public static void main(String[] args) {

---- C O D E   O M I T T E D ----
		for (int i = 0; i < e.length; i++) {

---- C O D E   O M I T T E D ----
		}


---- C O D E   O M I T T E D ----
		Invoice[] inv = new Invoice[4];
		inv[0] = new Invoice("ABC Co.", 456.78);
		inv[1] = new Invoice("XYZ Co.", 1234.56);
		inv[2] = new Invoice("Hello, Inc.", 999.99);
		inv[3] = new Invoice("World, Ltd.", 0.43);

		CheckPrinter.printChecks(e);
		CheckPrinter.printChecks(inv);
	}

}

The last several lines of code create an array of invoices, then use the CheckPrinter to print employees and invoices separately. It would also be possible to create an array of Payable objects, and add in the elements from both the employees and invoices arrays, but that seems like an unneccessary complication for this application.

Next