0

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?

2
  • A class that implements Printable is a class that is declared as implementing Printable. The method parameter will be an array of that type. Commented Dec 16, 2013 at 21:57
  • 1
    void method(Printable[] objects) { ... } Commented Dec 16, 2013 at 21:57

3 Answers 3

2

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

public static void print(Printable[] printables)
Sign up to request clarification or add additional context in comments.

Comments

2

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
}

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.