(内部类)编写一个Java程序,要求在程序中定义一个School类,在School类中定义一个内部类Student,分别创建这两个类的对象,访问各个对象中的方法,输出各种结果;
时间: 2024-03-19 17:46:26 浏览: 6
可以尝试以下代码:
```java
public class School {
private String name;
public School(String name) {
this.name = name;
}
public void showInfo() {
System.out.println("学校名称:" + name);
}
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public void showInfo() {
System.out.println("学生姓名:" + name);
System.out.println("所在学校:" + School.this.name);
}
}
public static void main(String[] args) {
School school = new School("清华大学");
school.showInfo();
School.Student student = school.new Student("张三");
student.showInfo();
}
}
```
在该程序中,我们定义了一个外部类 `School` 和一个内部类 `Student`。在 `School` 类中,我们定义了一个属性 `name` 和一个方法 `showInfo`,在该方法中输出学校的名称。在 `Student` 类中,我们定义了一个属性 `name` 和一个方法 `showInfo`,在该方法中输出学生的姓名和所在学校的名称。注意,在 `Student` 类中使用 `School.this.name` 来访问外部类中的属性。
在 `main` 方法中,我们分别创建了一个 `School` 类的对象 `school` 和一个 `Student` 类的对象 `student`,并调用了它们的方法输出信息。注意,在创建 `Student` 类的对象时,我们使用了 `school.new` 来实例化内部类对象。