Java 方法与实现接口的对象?
我有这个练习我想做,但我有点挣扎。 它说: “编写一个静态方法print,它接受一个对象数组 类实现可打印,并打印数组中的每个元素,一个 每行元素。通过将其放置在其他空类中进行检查 并进行编辑。”Java 方法与实现接口的对象?,java,Java,我有这个练习我想做,但我有点挣扎。 它说: “编写一个静态方法print,它接受一个对象数组 类实现可打印,并打印数组中的每个元素,一个 每行元素。通过将其放置在其他空类中进行检查 并进行编辑。” 如何编写一个方法,作为实现接口的参数对象,我假设我需要使用“implements Printable”,但是在哪里呢?我想不出来。。我知道在课堂上怎么做,但是。。。方法?您的静态方法需要接受一个可打印的数组作为其参数,例如 public static void print(Printable[] pr
如何编写一个方法,作为实现接口的参数对象,我假设我需要使用“implements Printable”,但是在哪里呢?我想不出来。。我知道在课堂上怎么做,但是。。。方法?您的静态方法需要接受一个可打印的数组作为其参数,例如
public static void print(Printable[] printables)
静态方法需要接受一个Printable数组作为其参数,例如
public static void print(Printable[] printables)
只需将接口用作数组的类型。像这样:
public static void print(Printable[] objectArray) {
//All objects in objectArray implement the interface Printable
}
只需将接口用作数组的类型。像这样:
public static void print(Printable[] objectArray) {
//All objects in objectArray implement the interface Printable
}
此练习要求您执行三项任务:
Printable
*Printable[]
作为参数Printable
main
方法中,创建一个Printable
数组,并用步骤3中定义的类的实例填充该数组public interface Printable {
void print();
}
下面是实现Printable
的类的建议:
public class TestPrintable implements Printable {
public void print() {
System.out.println("Hello");
}
}
静态方法应具有如下签名:
public static void printAll(Printable[] data) {
... // Write your implementation here
}
public void main(String[] args) {
Printable[] data = new Printable[] {
new TestPrintable()
, new TestPrintable()
, new TestPrintable()
};
printAll(data);
}
测试可以如下所示:
public static void printAll(Printable[] data) {
... // Write your implementation here
}
public void main(String[] args) {
Printable[] data = new Printable[] {
new TestPrintable()
, new TestPrintable()
, new TestPrintable()
};
printAll(data);
}
*,但它有不同的用途。此练习要求您执行三项任务:
Printable
*Printable[]
作为参数Printable
main
方法中,创建一个Printable
数组,并用步骤3中定义的类的实例填充该数组public interface Printable {
void print();
}
下面是实现Printable
的类的建议:
public class TestPrintable implements Printable {
public void print() {
System.out.println("Hello");
}
}
静态方法应具有如下签名:
public static void printAll(Printable[] data) {
... // Write your implementation here
}
public void main(String[] args) {
Printable[] data = new Printable[] {
new TestPrintable()
, new TestPrintable()
, new TestPrintable()
};
printAll(data);
}
测试可以如下所示:
public static void printAll(Printable[] data) {
... // Write your implementation here
}
public void main(String[] args) {
Printable[] data = new Printable[] {
new TestPrintable()
, new TestPrintable()
, new TestPrintable()
};
printAll(data);
}
*,但它有不同的用途。实现
可打印
的类是声明为实现可打印
的类。方法参数将是该类型的数组。void方法(可打印[]对象){…}
实现Printable
的类是声明为实现Printable
的类。方法参数将是该类型的数组。void方法(可打印的[]对象){…}