Chris Dobkowski
Chris Dobkowski

Reputation: 325

Method with objects that implement an interface?

I have this exercise I want to do, but I struggle a bit with it. It says:

"Write a static method print which takes an array of objects whose class implements Printable, and prints each element in the array, one element per line. Check it by placing it in an otherwise empty class and compiling it. "

How to write a method that takes as parameter objects that implement an interface, I assume I need to use "implements Printable" but where? Can't figure it out.. I know how to do that in a class but... method?

Upvotes: 0

Views: 1688

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The exercise requires you to perform three tasks:

  1. Define an interface called Printable *
  2. Write a static method that takes Printable[] as a parameter
  3. Write an otherwise empty class that implements Printable
  4. In your main method, create an array of Printable, and fill it with instances of the class defined in step 3
  5. Pass the array defined in step 4 to the static method defined in step 2 to check that your code works correctly.

Here is a suggestion for an interface:

public interface Printable {
    void print();
}

Here is a suggestion for the class implementing Printable:

public class TestPrintable implements Printable {
    public void print() {
        System.out.println("Hello");
    }
}

The static method should have a signature that looks like this:

public static void printAll(Printable[] data) {
    ... // Write your implementation here
}

The test can looks like this:

public void main(String[] args) {
    Printable[] data = new Printable[] {
        new TestPrintable()
    ,   new TestPrintable()
    ,   new TestPrintable()
    };
    printAll(data);
}


* Java defines an interface called Printable, but it serves a different purpose.

Upvotes: 1

MAV
MAV

Reputation: 7457

Just use the interface as a type for the array. Like this:

public static void print(Printable[] objectArray) {
    //All objects in objectArray implement the interface Printable
}

Upvotes: 2

Joe Attardi
Joe Attardi

Reputation: 4521

Your static method needs to accept an array of Printable as its argument, e.g.

public static void print(Printable[] printables)

Upvotes: 2

Related Questions