(内部类)编写一个Java程序,要求在程序中定义一个School类,在School类中定义一个内部类Student,分别创建这两个类的对象,访问各个对象中的方法,输出各种结果
时间: 2024-03-19 08:45:59 浏览: 56
以下是示例代码:
```
public class School {
private String name;
public School(String name) {
this.name = name;
}
public void printSchoolName() {
System.out.println("School Name: " + name);
}
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public void printStudentName() {
System.out.println("Student Name: " + name);
}
public void printSchoolAndStudentName() {
System.out.println("School Name: " + School.this.name);
System.out.println("Student Name: " + name);
}
}
}
```
在该代码中,School类定义了一个内部类Student,内部类中有一个printSchoolAndStudentName方法,可以打印出外部类School和内部类Student的名称。现在可以创建这两个类的对象并访问它们的方法来输出各种结果:
```
public class Test {
public static void main(String[] args) {
School school = new School("ABC School");
school.printSchoolName();
School.Student student = school.new Student("Tom");
student.printStudentName();
student.printSchoolAndStudentName();
}
}
```
在该代码中,首先创建了一个School对象,并使用该对象调用printSchoolName方法来打印学校名称。然后创建了一个Student对象,并使用该对象调用printStudentName和printSchoolAndStudentName方法来打印学生姓名和学校名称。输出结果应该如下:
```
School Name: ABC School
Student Name: Tom
School Name: ABC School
Student Name: Tom
```
阅读全文