对象与对象

对象里面添加一个对象作为属性

一个学生类里面,添加一个电脑类,作为它的属性

1
2
3
4
5
学生类
public class student {
public String name;
public comper cer; //电脑类
}
1
2
3
4
5
6
电脑类
public class comper {
public String name;
public String cpu;
public String gpu;
}

使用的话,就和普通变量一样使用

1
2
3
4
5
comper cper = new comper();
cper.cpu = "酷睿";

student stud = new student();
stud.cer = cper; // 将上面的电脑类作为值赋给学生类的属性(cer)

调用就是stud.cer.cpu。这个还是好理解的

将对象数组作为对象的属性

是不是听起来听拗口的

写出来还是好理解

1
2
3
4
5
6
7
8
9
10
11
public class comper {
public String name;
public String cpu;
public String gpu;

public comper(String name, String cpu, String gpu) {
this.name = name;
this.cpu = cpu;
this.gpu = gpu;
}
}

将上面的学生类拿过来用

1
2
3
4
5
学生类
public class student {
public String name;
public comper[] cer; //用数组存储多个电脑类
}

这里cer使用起来和前面的对象数组的效果是一样的

1
2
3
4
5
6
student stud = new student();
stud.cer = new comper[]{
new comper("n1", "zhang@email.com", "x"),
new comper("n2", "zhang@email.com", "y")
};
System.out.println(stud.cer[0].name);//n1