java多态性、包、,
大家好,我正在做作业,我被卡住了,所以我需要一些反馈
我在一个包中有一个抽象类Gear和enum类型信息,然后有InfoTest,它使用assert和junit测试来测试Gear和信息的正确性
问题在于信息测试。我有Info g = some Value;
和g.getWeight()
哪个方法在Gear类中,我无法通过Info对象从InfoTest访问getWeight()方法
所以我想知道是否有一种方法可以通过InfoTest中的Info对象访问getWeight(),或者我的老师犯了一个错误。萨克斯
好的,这里是一些代码示例
public abstract class 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()); }
>
> }
# 1 楼答案
问题是Info是一个枚举类,它目前无法访问Gear类。很难准确地计算出你的家庭作业的范围
像这样的。。。 首先,创建另一个扩展抽象类的类(比如SubGear)
在这个类中,我们有一个构造函数,它接受Info对象,并像这样填充Gear类中的字段:
然后在测试中创建一个新的SubGear对象,以便根据需要访问getWeight