为外部类Person添加一个内部类Pet,为Pet添加方法variety()以表示其品种,并对其进行实例化和打印输出。
时间: 2024-05-10 20:16:51 浏览: 14
好的,以下是代码实现:
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void introduce() {
System.out.println("My name is " + name + ", and I am " + age + " years old.");
}
public class Pet {
private String variety;
public Pet(String variety) {
this.variety = variety;
}
public void variety() {
System.out.println("My pet's variety is " + variety);
}
}
public static void main(String[] args) {
Person person = new Person("Tom", 20);
person.introduce();
Person.Pet pet = person.new Pet("Dog");
pet.variety();
}
}
```
在这个例子中,我们为 `Person` 类添加了一个内部类 `Pet`,并在 `Pet` 类中添加了一个 `variety()` 方法,用于表示宠物的品种。我们在 `main` 方法中对 `Pet` 类进行了实例化,并调用 `variety()` 方法来打印输出宠物的品种信息。
注意:由于 `Pet` 类是 `Person` 类的内部类,因此在实例化 `Pet` 类时,需要使用 `Person` 类的实例来进行实例化。因此,在 `main` 方法中,我们首先实例化了 `Person` 类,然后使用 `Person` 类的实例来实例化 `Pet` 类。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)