Student(day_07)
class Student
①给这个类定义属性
②在类中,主方法外定义一个打印属性值的方法
public void print(){
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
System.out.println("性别:" + sex);
}
③定义一个对象数组
注意:这个类是Student类,那么对象也是student类型的。所以数组要存一个student类型的元素,所以数组也是Studen类型的。
④使用循环遍历数组,在遍历的过程中,给属性赋值。注意:要在循环内部定义对象,没循环一次定义一个新的对象,然后用 对象.属性 从控制台接收输入的对应的属性。每一轮循环结束,就把这个对象放到数组里。
for(int i = 0; i < stu.length; i++){
//定义对象
Student s = new Student();
System.out.println("请输入学生姓名:");
s.name = sc.next();
System.out.println("请输入学生年龄:");
s.age = sc.nextInt();
System.out.println("请输入学生性别:");
s.sex = sc.next();
//将对象放到数组里
stu[i] = s;
}
注意:s是一个引用类型的变量,里面存放的是地址。每轮新new一个s,然后将s放到数组中,那么数组中就都是这些对象(地址),分别指向堆空间中对应的属性
注意:
Student a = new Student();
a.age = 5;
这样是对的。和下面的对比一下
//定义一个对象数组
Student[] stu = new Student[5];
stu[0].age = 5;
这样会报"空指针异常"。因为我只给stu这个变量new了空间。stu[0]还是空值,所以不能让它去.age。
Emp(day_08)
class Emp
先定义这个类的属性
①然后写无参构造函数,有参构造函数。构造函数是用来创建对象的。
//无参构造函数
public Emp(){
}
//有参构造函数
public Emp(String eid, String name, int age, String phone, String job, String dept){
this.eid = eid;
this.name = name;
this.age = age;
this.phone = phone;
this.job = job;
this.dept = dept;
}
注意:如果形参名字和属性的名字相同,那么赋值的时候:右边是形参的名字,左边是是属性名,但需要在属性名前加上this,用来区别那个是形参,那个数属性。
②然后写get,set方法:get方法用来获取值,所以要有返回值。set方法时用来设置值,所以要有形参。
③写toString方法:用来输出这个类的所有属性。
class EmpTest
①用有参构造函数来创建对象,并在创建对象是给属性赋值。
Emp e1 = new Emp(