大家好,我正在做作业,而且我遇到了困难,所以我需要一些反馈。
我在一个包中有一个抽象类Gear和枚举类型Info,然后我有InfoTest,它使用assert和junit测试来测试Gear和Info的正确性。
InfoTest中存在问题。我有Info g = some Value;
然后g.getWeight()
哪个方法在Gear类中,我无法通过Info对象访问InfoTest中的getWeight()方法。
所以我想知道是否有办法使用InfoTest中的Info对象访问getWeight(),或者我的老师犯了一个错误。 Thaks。
OKKKKKKKKKKK这里有一些代码示例。
公共抽象类Gear {
/** * weight stores the weight of the item in kg */ protected int weight; /** * code store the code for the item (bedding, food, medical or sanitary, but it is better to use array. */ protected char code; /**getWeight gets the weight of the item. * * @return weight */ public int getWeight() { return weight; } /**setWeight sets the weight for the item * * @param weight */ public void setWeight(int weight) { this.weight = weight; } /**getCode() gets the code of the item. * * @return code */ public char getCode() { return code; } /**setCode sets the code of the item. * * @param code */ public void setCode(char code) { this.code = code; } }
public enum Info {
/** * BLANKETS represent the blankets. */ BLANKETS, /** * PILLOWS represent the pillows */ PILLOWS, /** * FOOD represent the food */ FOOD, /** * MEDKIT represent the medical kit. */ MEDKIT, /** * OXYGEN represent the oxygen */ OXYGEN, /** * NAPKINS represent the napkins. */ NAPKINS, /** * SICKNESSBAG represent the sickness bags. */ SICKNESSBAG }
> public class InfoTest {
/**
> * Test of getWeight() method, of class Info.
> */
> @Test
> public void testGetWeight() {
> System.out.print("\tChecking weights in Info");
> Info g = Info.BLANKETS;
> final int expectedValue1 = 2;
> assertEquals(expectedValue1, g.getWeight()); }
>
> }
答案 0 :(得分:1)
问题是Info是一个枚举类,它目前无法访问Gear类。很难准确地确定你的作业范围是什么。
像这样...... 首先创建另一个扩展抽象类的类(类似于SubGear)
public SubGear extends Gear
在这个类中有一个构造函数,它接受Info对象并且还填充Gear类中的字段,如下所示:
public SubGear (Info info, int weight, char code){
this.code = code;
this.weight= weight;
this.info = info
}
public void setInfo(Info info){
this.info = info;
}
public Info getInfo(){
return info;
}
然后在您的测试中创建一个新的SubGear对象,以便根据需要访问getWeight