(1)
- 描述一个学生类,学生具备姓名、学号、性别、三个公共的属性,学生都具备吃饭与学习的行为。
- 测试类中为学生类的属性赋值、调用学生的方法
- 描述一个电脑类,具有属性:cpu,网卡,显卡,声卡,内存 方法:上网
- 描述学生拥有一台电脑
public class Student {
//属性/成员变量/全局变量/实例变量 访问的方式: "对象名." 空引用 null
//有可能会出现NPE
public String studentName;
public int studentNo;
public char gender;
//学生拥有一台电脑
public Computer computer;
//方法/行为/成员方法/实例方法 访问的方式: "对象名."
public void eat() {
System.out.println(studentName + "在吃饭。。。。。。。。。。");
}
public void study() {
if (computer == null) {
System.out.println("请先对computer属性赋值");
return;
}
System.out.println(studentName + "正在学习............");
//学生可以使用电脑学习
//调用Computer类里面的 online()
computer.online(studentName);
}
//构造方法
//作用: 为了初始化成员变量的数据
public Student() {
}
public Student(String studentName, int studentNo, char gender) {
this.studentName = studentName;
this.studentNo = studentNo;
this.gender = gender;
}
}
class Computer {
public String brandName;
public void online(String studentName) {
System.out.println(studentName + "正在使用" + brandName + "上网学习.........");
}
public Computer(String brandName) {
this.brandName = brandName;
}
public Computer() {
}
}
class StudentTest {
public static void main(String[] args) {
//创建对象
/* Student student = new Student();
student.studentName = "张三";
student.studentNo = 1001;
student.gender = '男';*/
Student student = new Student("张三", 1001, '男');
System.out.println(student.studentName);
System.out.println(student.studentNo);
System.out.println(student.gender);
student.computer = new Computer("DELL电脑");
//student.eat();
student.study();
}
}









