有一个包(Bag)类,属性成员有:颜色,产商 有一个书包(SchoolBag)类,属性成员有:颜色,产商,是否双肩背,适用年龄 正确理解如上2个类的关系,并自行设计添加相应的方法。并写一个测试类进行测试。java
时间: 2024-02-18 21:00:57 浏览: 25
Bag类和SchoolBag类之间的关系是继承关系,即SchoolBag类继承了Bag类的属性,并在此基础上增加了新的属性和方法。
下面是Bag类的代码实现:
```java
public class Bag {
private String color;
private String manufacturer;
public Bag(String color, String manufacturer) {
this.color = color;
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public String getManufacturer() {
return manufacturer;
}
}
```
下面是SchoolBag类的代码实现:
```java
public class SchoolBag extends Bag {
private boolean isDoubleShoulder;
private int suitableAge;
public SchoolBag(String color, String manufacturer, boolean isDoubleShoulder, int suitableAge) {
super(color, manufacturer);
this.isDoubleShoulder = isDoubleShoulder;
this.suitableAge = suitableAge;
}
public boolean isDoubleShoulder() {
return isDoubleShoulder;
}
public int getSuitableAge() {
return suitableAge;
}
public void carry() {
System.out.println("背起了书包");
}
}
```
在SchoolBag类中,我们新增了两个属性isDoubleShoulder和suitableAge,并且在构造函数中调用了父类Bag的构造函数。
新增了carry()方法,表示背起了书包。
下面是测试类的代码实现:
```java
public class Test {
public static void main(String[] args) {
SchoolBag schoolBag = new SchoolBag("blue", "Nike", true, 10);
System.out.println(schoolBag.getColor());
System.out.println(schoolBag.getManufacturer());
System.out.println(schoolBag.isDoubleShoulder());
System.out.println(schoolBag.getSuitableAge());
schoolBag.carry();
}
}
```
在测试类中,我们创建了一个SchoolBag对象,并打印出了其属性值,同时调用了carry()方法。运行测试类,输出如下:
```
blue
Nike
true
10
背起了书包
```
说明我们的类和方法实现是正确的。