定义一个接口IPet,包含两个方法:play(和 getName()。(4)在Cat类中实现IPet接口,并实现play()方法和 getName()方法。
时间: 2024-03-20 21:42:42 浏览: 9
好的,下面是实现代码:
```
// 定义接口IPet
interface IPet {
void play();
String getName();
}
// Cat类实现IPet接口
class Cat implements IPet {
private String name;
Cat(String name) {
this.name = name;
}
@Override
public void play() {
System.out.println(name + " is playing with a ball of yarn.");
}
@Override
public String getName() {
return name;
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
IPet pet = new Cat("Luna");
pet.play();
System.out.println("My pet's name is " + pet.getName());
}
}
```
在上面的代码中,我们定义了一个接口`IPet`,包含了`play()`和`getName()`两个方法。然后我们让`Cat`类实现了`IPet`接口,并实现了`play()`和`getName()`方法。
最后我们在`Main`类中进行了测试,创建了一个`Cat`对象并赋值给`IPet`类型的变量`pet`,然后分别调用了`play()`和`getName()`方法。输出结果为:
```
Luna is playing with a ball of yarn.
My pet's name is Luna
```
说明`Cat`类成功地实现了`IPet`接口。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)