首页 > 解决方案 > 如何覆盖子类中超类的属性?

问题描述

我很确定我的代码应该可以正常工作,但是我的学习平台中的测试失败了,说明我的子类中的构造函数“应该将描述设置为‘未分类’以外的值”

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

避免该问题的一种方法是将父类中的描述设置为“”而不是“未分类”,但需要将其设置为“未分类”。

我不知道是什么导致它表现得那样。

标签: javainheritancecomputer-science

解决方案


我怀疑测试希望你在下面做:

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

我假设测试希望您覆盖构造函数本身中的属性,而不是显式设置它


推荐阅读