繁体   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