一、题1
1.1 问题描述
(1)使用继承编写人类、教师、学生类的实体类。(2)编写测试类,实例化教师和学生类对象并显示。
1.2 代码块
public class Human {
private String name;
private String age;
//构造方法
public Human() {}
public Human(String name,String age) {
this.setName(name);
this.setAge(age);
}
//age与name的get,set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
//父类方法
public void work() {
System.out.printf("这是父类的方法");
}
}
public class Students extends Human {
//构造方法
public Students(String name, String age) {
super(name, age);//调用父类构造方法传递参数
}
//重写父类方法
public void work() {
System.out.println("学生爱读书");
}
}
public class Teachers extends Human {
//构造方法
public Teachers(String name, String age) {
super(name,age);
}
//重写父类方法
public void work() {
System.out.println("老师爱教书");
}
}
public class TestDemo {
public static void main(String[] args) {
System.out.println("调用setName方法(顺序:学生类,老师类)");
Students s=new Students("张三","21");
System.out.println(s.getName());
s.work();
Teachers t=new Teachers("赵老师","35");
System.out.println(t.getName());
t.work();
}
}
1.3 运行截图
二、题2
2.1 问题描述
有一个水果箱(Box),箱子里装有水果(Fruit),每一种水果都有不同的重量和颜色,水果有:苹果,梨,桔 子。每个苹果(Apple)都有不同的重量和颜色,每个桔子(Orange)都有不同的重量和颜色,每个梨(Pear)都有不同的重量和颜色。可以向水果箱(Box)里添加水果(addFruit),也可以取出水果(getFruit),还可以显示水果的重量和颜色。编写代码实现上述功能。
2.2 代码块
public class Fruit {
//属性
private String name;
private String color;
private int weight;
//set get方法
public String getColor() {
return color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setColor(String color) {
this.color = color;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
//public Fruit() {} //构造方法
public Fruit(String name,String color,int weight) {
this.name=name;
this.color = color;
this.weight = weight;
}
//显示信息
public String toString() {
return getName()+" "+getWeight()+" "+getColor();
}
}
public class Apple extends Fruit {
public Apple(String name,String color,int weight) {
super(name,color,weight);
}
}
public class Orange extends Fruit {
public Orange(String name,String color,int weight) {
super(name,color,weight);
}
}
public class Pear extends Fruit{
public Pear(String name,String color,int weight) {
super(name,color,weight);
}
}
import java.util.ArrayList;
public class Box {
ArrayList<Fruit> flist = new ArrayList<Fruit>();
//添加水果方法
public void addFruit(Fruit fruit) {
flist.add(fruit);
}
//取出水果方法
public void getFruit(Fruit fruit) {
flist.remove(fruit);
}
//显示
public void show() {
for(Fruit fruit : flist) {
System.out.println(fruit);
}
}
public static void main(String[] args) {
Fruit f1 = new Apple("apple","red",3);
Fruit f2 = new Pear("pear","yellow",6);
Fruit f3 = new Orange("orange","yellow",8);
Box b = new Box();
b.addFruit(f1);
b.addFruit(f2);
b.addFruit(f3);
System.out.println("显示水果:");
b.show();
b.getFruit(f3);
System.out.println("取出水果后:");
b.show();
}
}