面向对象day02,作业学生类,电脑类

2022-11-29,,,,

学生类,电脑类,测试类

学生类:解释都写在注释里面
public class Student {
public String name;
public int id;
public char gender;
// 让computer类充当学生类的属性,利用这个变量充当对象来调用类里面的方法和属性
public Computer computer;
// public Computer computer=new Computer("DEll");
//这是实例变量可以解决空指针异常的问题
// 但是每次new都会新建一个变量来充当对象,占据空间会很大,所以只初始化就可以 public Student() {
}
public Student(String name, int id, char gender, Computer computer) {
this.name = name;
this.id = id;
this.gender = gender;
this.computer = computer;
} public void eat(){
System.out.println(name+"在吃饭");
}
public void study(){
if(computer==null){
System.out.println("computer不能为null");
return;
}
computer.surf(name);
System.out.print("学习");
}
}
电脑类
public class Computer {
public String brand;
//定义一个变量是电脑品牌
public Computer(String brand) {
this.brand = brand;
}//有参数的构造方法
public Computer() {
}//无参的构造方法
public void surf(String sname){
System.out.print(sname+"正在使用"+brand+"的电脑上网");
}//上网的方法
}
测试类

测试类是运行的入口,main函数在该类

public class StudenCom {
public static void main(String[] args) {
Student s1=new Student();
s1.name="张三";
s1.id=3627;
s1.gender='男';
/*Computer mycomputer=s1.computer;
System.out.println(mycomputer+"mycomputer");
这上下两行输出的都是空值,说明还是没有给他赋值
mycomputer=new Computer("DEll");
s1.computer=mycomputer;加上这一行将mycomputer指向s1的地址或者可以直接用下面:*/
s1.computer=new Computer("dell");
s1.study();
}
}

面向对象day02,作业学生类,电脑类的相关教程结束。

《面向对象day02,作业学生类,电脑类.doc》

下载本文的Word格式文档,以方便收藏与打印。