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?
3 Answers 3
Your static method needs to accept an array of Printable as its argument, e.g.
public static void print(Printable[] printables)
Comments
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
The exercise requires you to perform three tasks:
- Define an interface called
Printable* - Write a static method that takes
Printable[]as a parameter - Write an otherwise empty class that implements
Printable - In your
mainmethod, create an array ofPrintable, and fill it with instances of the class defined in step 3 - 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.
Printableis a class that is declared as implementingPrintable. The method parameter will be an array of that type.void method(Printable[] objects) { ... }