概念解析:
对象中的对象:
在对象中拥有属性,其属性类型是其他类
对象数组:
数组的类型是某个类。数组中的值是对象。
下面通过具体代码体现两个概念
先建立一个学生类
public class Student {
public String name;
public String sex;
public int age;
public String stuNo;
//在学生类中的老师类 对象中的对象
public Teacher teacher;
// public static Student[] stu;
//toString 可使在main方法中直接打印实例化的对象名称 不再显示地址值
而是这个方法的返回值
public String toString(){
return "学生姓名:"+name+"\t性别"+sex+"\t年龄:"+age+"\t学分:"+stuNo+"\t老师姓名:"+teacher.name;
}
}
再建立一个老师类
public class Teacher {
public String name;
public String sex;
public int age;
public int workYear;
public String major;
//对象数组
public Student[] students;
public String toString(){
return "教师姓名:"+name+"\t性别:"+sex+"\t年龄:"+age+"\t工作年限:"+workYear+"\t专业:"+major;
}
public void show(){
for(int i = 0; i<students.length;i++){
Student stu = students[i];
System.out.println(stu);
}
}
public void show2(){
for(Student stu : students){
System.out.println(stu);
}
}
}
下面在测试中实例化两个类
public class Test {
public static void main(String[] args) {
//实例化一个学生;张大狼
Student stu1 = new Student();
stu1.name = "张大朗";
stu1.sex = "女";
stu1.age = 17;
stu1.stuNo = "100";
Student stu2 = new Student();
stu2.name = "貂蝉";
stu2.sex = "女";
stu2.age = 16;
stu2.stuNo = "100";
Student stu3 = new Student();
stu3.name = "李元芳";
stu3.sex = "女";
stu3.age = 21;
stu3.stuNo = "100";
Teacher tea = new Teacher();
tea.name = "王思聪";
tea.age = 32;
tea.sex = "女";
tea.workYear = 8;
tea.major = "纪检委";
stu1.teacher = tea;
stu2.teacher = tea;
stu3.teacher = tea;
//实例化一个学生数组
Student[] stu = new Student[]{stu1,stu2,stu3};
//赋值给老师类中的学生数组
tea.students = stu;
tea.students[0] = stu1;
tea.students[1] = stu2;
tea.students[2] = stu3;
System.out.println(tea.name);
tea.show();
System.out.println("*****************");
tea.show2();
System.out.println("***************************************");
//貂蝉的老师是谁?
System.out.println(stu2.name+"的老师是:"+stu2.teacher.name);
//老师的学生有?
System.out.println(tea.name+"的学生有:");
tea.show2();
}