Reputation: 325
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
Reputation: 726479
The exercise requires you to perform three tasks:
Printable
*Printable[]
as a parameterPrintable
main
method, create an array of Printable
, and fill it with instances of the class defined in step 3Here 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);
}
Printable
, but it serves a different purpose.
Upvotes: 1
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
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