(内部类)编写一个Java程序,要求在程序中定义一个School类,在School类中定义一个内部类Student,分别创建这两个类的对象,访问各个对象中的方法,输出各种结果;
时间: 2024-03-19 09:46:31 浏览: 19
好的,这是一个使用内部类的Java程序示例:
```
public class School {
// School类中定义一个内部类Student
class Student {
private String name;
public Student(String name) {
this.name = name;
}
public void study() {
System.out.println(name + " is studying");
}
}
public static void main(String[] args) {
// 创建School类的对象
School school = new School();
// 创建Student类的对象
School.Student student1 = school.new Student("Tom");
School.Student student2 = school.new Student("Jerry");
// 访问各个对象中的方法,输出各种结果
student1.study(); // 输出 "Tom is studying"
student2.study(); // 输出 "Jerry is studying"
}
}
```
在这个例子中,我们定义了一个School类,其中包含一个内部类Student。我们在main方法中创建了School类的对象school,然后使用school对象创建了两个Student对象:student1和student2。最后,我们调用各个对象中的方法study()来输出各种结果。注意,由于Student类是School类的内部类,因此我们需要使用"School.Student"来创建Student对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)