1.
.用 Java 程序编写完成下列问题
Person 类
(1) 属性:姓名、年龄、性别
(2) 方法有吃饭和睡觉。
Student 类
(1) 属性:学号、班级
(2) 方法:学习
Teacher 类
(1) 属性:教师编号、教师级别
(2) 方法:授课
定义 Test 类使用主函数测试以上三个类
public class Person {
//属性
public String name;
public int age;
public String sex;
//构造函数
public Person() {
}
public Person(String name,int age,String sex) {
this.name=name;
this.age=age;
this.sex=sex;
}
//行为方法
public void eat() {
System.out.println(name+"开始吃饭了");
}
public void sleep() {
System.out.println(name+"累了,开始睡觉");
}
}
public class Student {
//属性
public String num;
public int level;
//构造函数
public Student() {
}
public Student(String num,int level) {
this.num=num;
this.level=level;
}
//行为方法
public void study() {
System.out.println("学号为"+num+"的"+level+"年级学生正在学习");
}
}
public class Teacher {
//属性
public String num;
public int level;
//构造函数
public Teacher() {
}
public Teacher(String num,int level) {
this.num=num;
this.level=level;
}
//行为方法
public void teach() {
System.out.println("编号为"+num+"的"+level+"年级教师开始上课了");
}
}
public class Test {
public static void main(String[] args) {
//实例化
Person a = new Person("小明",18,"男");
Teacher b = new Teacher("221222",3);
Student c = new Student("33",3);
//调用方法
a.eat();
a.sleep();
b.teach();
c.study();
}
}
2.
定义学生类
类中有属性:学号、姓名、性别、年龄
有方法:学习、玩游戏、获取学生信息的方法
有构造方法:
无参的构造方法
带有参数的构造方法,在创建对象的时候初始化各个属性值
定义一个长度为5的数组,用户在控制台录入5个学生的信息保存到数组中
遍历数组打印5个学生的个人信息
Student[] arr = new Student[5];
public class Student {
//属性
public String num;
public String name;
public int age;
public String sex;
//构造函数
public Student() {
}
public Student(String num,String name,int age,String sex) {
this.num=num;
this.name=name;
this.age=age;
this.sex=sex;
}
//行为方法
public String get() {
return "这个"+sex+"生是学号为"+num+"的"+age+"岁的"+name;
}
public void study() {
System.out.println(name+"正在学习");
}
public void play() {
System.out.println(name+"累了,正在玩游戏");
}
}
public class Test {
public static void main(String[] args) {
//定义数组,输入值
Student arr[]=new Student[5];
arr[0] = new Student("11","小明",17,"男");
arr[1] = new Student("21","小蓝",17,"男");
arr[2] = new Student("31","小美",17,"女");
arr[3] = new Student("41","小强",18,"男");
arr[4] = new Student("41","小丽",18,"女");
//强化for循环遍历元素
for(Student i:arr) {
System.out.println(i.get());
i.study();
i.play();
}
}
}