Java内部类例子并解释
设计一个学生类,包含学生的名字,学号,性别,生日,地址。
设计一个内部类课程,包含多少门课程和具体课程。
结构:
外部类:students
成员变量:name,code,sexy,birthday,address
构造函数:变量的get和set方法
实现方法:1.通过tostring方法让对象以字符串形式输出name,code,sexy,birthday,address
2.获得学生课程和课程数目的方法
内部类:course
成员变量:courses,coursenum
构造函数:1.通过get()方法获得课程数组中的课程
2.通过getinfo()方法按字符串形式输出课程数目和具体课程名称
代码:
//设计一个学生类
public class students {
//创建成员变量
private String name;
private String code;
private String sexy;
private String birthday;
private String address;
//通过设置器和访问器来设置对象参数
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getSexy() {
return sexy;
}
public void setSexy(String sexy) {
this.sexy = sexy;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
//通过tostring方法让对象以字符串形式输出的方法
public String tostring(){
String infor = "学生姓名:"+name+""+"学号:"+code+""+"性别:"+sexy+""+"出生年月:"+birthday+""+"家庭住址:"+address;
return infor;
}
//设置学生课程的方法
public void setstudentcourse(String[] courses){
new course(courses); //创建内部类的对象来实现设置学生课程的方法
}
//内部类的创建,把内部类作为外部类的一个成员
private class course {
//创建两个成员变量
private String[] courses;
private int coursenum;
//内部类的构造器
public course(String[] course) {
courses = course;
coursenum = course.length;
getinfo();