5、(内部类)编写一个Java程序,要求在程序中定义一个School类,在School类中定义一个内部类Student,分别创建这两个类的对象,访问各个对象中的方法,输出各种结果;
时间: 2024-03-20 18:38:51 浏览: 45
编写一个JAVA程序,定义一个Student类
5星 · 资源好评率100%
以下是实现该程序的Java代码:
```
public class School {
private String name;
private int establishedYear;
public School(String name, int establishedYear) {
this.name = name;
this.establishedYear = establishedYear;
}
public String getName() {
return name;
}
public int getEstablishedYear() {
return establishedYear;
}
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static void main(String[] args) {
School school = new School("ABC School", 1990);
School.Student student = school.new Student("John", 15);
System.out.println("School Name: " + school.getName());
System.out.println("School Established Year: " + school.getEstablishedYear());
System.out.println("Student Name: " + student.getName());
System.out.println("Student Age: " + student.getAge());
}
}
```
在上面的代码中,我们定义了一个School类和内部类Student。School类包含一个name属性和establishedYear属性,以及相应的getter方法。Student类有name属性和age属性,以及相应的getter方法。在main方法中,我们实例化了School和Student对象,并访问了它们的各种方法,输出了各种结果。需要注意的是,我们使用了school.new Student()的方式创建了内部类的对象。
阅读全文