CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Interfaces

Interfaces
Interfaces
Use an interface as a parameter

How to use an interface as a parameter

  • You can declare a method parameter as an interface type. Then, you can pass any object that implements the interface to the parameter.
  • You can declare a variable as an interface type. Then, you can assign an instance of any object that implements the interface to the variable, and you can pass the variable as an argument to a method that accepts the interface type.

A printMultiple method that prints multiple copies of a Printable object

private static void printMultiple(Printable p, int count)
{
    for (int i = 0; i < count; i++)
        p.print();
}

Code that passes a Product object to the printMultiple method

Product product = new Product("java", "Murach's Beginning Java 2", 49.50);
printMultiple(product, 2);

Resulting output

Code:           java
Description:    Murach's Beginning Java 2
Price:          $49.50
Code:           java
Description:    Murach's Beginning Java 2
Price:          $49.50

Code that passes a Printable object to the printMultiple method

Printable product = new Product("java", "Murach's Beginning Java 2", 49.50);
printMultiple(product, 2);

Resulting output

Code:           java
Description:    Murach's Beginning Java 2
Price:          $49.50
Code:           java
Description:    Murach's Beginning Java 2
Price:          $49.50
Previous | Code | Implement | Inherit a class | Use an interface as a parameter | Use inheritance with interfaces | Next