java创建一个 `Print接口` ,在其中定义一个打印方法print,再创建两个类分别实现这个接口
时间: 2024-02-27 11:54:14 浏览: 73
好的,这是一个接口的问题,我可以帮你解答。
首先,我们需要创建一个 `Print` 接口,并在其中定义一个打印方法 `print`,代码如下:
```java
public interface Print {
void print();
}
```
接下来,我们需要创建两个类,分别实现这个接口。这里我们创建 `ConsolePrinter` 类和 `FilePrinter` 类,分别用于在控制台和文件中打印信息。
`ConsolePrinter` 类实现了 `Print` 接口,并在其中实现了 `print` 方法,用于在控制台中打印信息。代码如下:
```java
public class ConsolePrinter implements Print {
@Override
public void print() {
System.out.println("This is printed on console.");
}
}
```
`FilePrinter` 类同样实现了 `Print` 接口,并在其中实现了 `print` 方法,用于在文件中打印信息。代码如下:
```java
import java.io.FileWriter;
import java.io.IOException;
public class FilePrinter implements Print {
@Override
public void print() {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("This is printed in file.");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在 `FilePrinter` 类中,我们使用 `FileWriter` 类来向文件中写入信息。需要注意的是,在使用 `FileWriter` 时,需要使用 `try-catch` 语句处理可能出现的异常。
这样,我们就完成了 `Print` 接口的创建和两个类的实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)