簡體   English   中英

如何覆蓋子類中超類的屬性?

[英]How do I override an attribute from a super class in a subclass?

我很確定我的代碼應該可以正常工作,但是我的學習平台中的測試失敗,說明我的子類中的構造函數“應該將描述設置為‘未分類’以外的值”

Parent Class 
public class Rock
{
   int sampleNumber;
   String description;
   double weight;
  
   public Rock(int sampleNumber, double weight)
   {
       this.sampleNumber = sampleNumber;
       this.description = "Unclassified";
       this.weight = weight;
   }
   public void setSampleNumber( int sampleNumber ){
        this.sampleNumber = sampleNumber;
    }
  
   public int getSampleNumber(){
            return this.sampleNumber;
        }

   public void setDescription( String description ){
        this.description = description;
    }
    
   public String getDescription(){
        return this.description;
        }

   public void setWeight(double weight){
        this.weight = weight;
            }
          
   public double getWeight() {
        return this.weight;
                }

   public String toString()
   {
       return "The number of samples are: "+sampleNumber+
               "\nThe weight of the rock is: "+ weight+
               "\nThe description of rock type is: "+ description;
   }
}

子類之一(有 3 個,它們幾乎相同)

public class SedimentaryRock extends Rock
{
   public SedimentaryRock(int sampleNumber,int weight)
   {
       super(sampleNumber, weight);
   }
   public void setDescription( String description ){
        super.description = description;
    }
  
   public String getDescription(){
            return super.description;
        }
}

這是主類

public class DemoRocks
{
   public static void main(String[] args)
   {
       IgneousRock rock = new IgneousRock( 2, 200);
       rock.setDescription("andesite");
       System.out.println(rock.toString());
      
       SedimentaryRock rock2= new SedimentaryRock( 3, 300);
       rock2.setDescription("sandstone");
       System.out.println(rock2.toString());
      
       MetamorphicRock rock3=new MetamorphicRock( 4, 400);
       rock3.setDescription("quartzite");
       System.out.println(rock3.toString());
   }

}

輸出是:

The number of samples are: 2
The weight of the rock is: 200.0
The description of rock type is: andesite
The number of samples are: 3
The weight of the rock is: 300.0
The description of rock type is: sandstone
The number of samples are: 4
The weight of the rock is: 400.0
The description of rock type is: quartzite

避免該問題的一種方法是將父類中的描述設置為“ ”而不是“未分類”,但需要將其設置為“未分類”。

我不知道是什么導致它的行為如此。

我懷疑測試希望你在下面做:

    public SedimentaryRock(int sampleNumber,int weight) {
           super(sampleNumber, weight);
           super.setDescription("sedimentary");
    }

我假設測試希望您覆蓋構造函數本身中的屬性而不是顯式設置它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM