簡體   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