繁体   English   中英

多态,包,

[英]Polymorphism, packages,

大家好,我正在做作业,但被卡住了,所以我需要一些反馈。

我在一个包中有一个抽象类 Gear 和枚举类型 Info,然后我有 InfoTest,它使用 assert 和 junit 测试来测试 Gear 和 Info 的正确性。

问题出在 InfoTest 中。 我有Info g = some Value; 然后g.getWeight()哪个方法在 Gear 类中,我无法通过 Info 对象从 InfoTest 访问 getWeight() 方法。

所以我想知道是否有办法使用来自 InfoTest 的 Info 对象访问 getWeight() 或者我的老师犯了一个错误。 谢谢。

OKKKKKKKKKKK 这里是一些代码示例。

公共抽象类齿轮{

 /** * 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; } }

公共枚举信息{

 /** * 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()); }
> 
> }
  

问题是 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM