如何解决如何覆盖子类中超类的属性?
我很确定我的代码应该可以正常工作,但是学习平台中的测试未能说明子类中的构造函数“应将描述设置为'Unclassified'以外的值”
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
避免该问题的一种方法是将父类中的描述设置为“”,而不是“未分类”,但需要将其设置为“未分类”。
我不知道是什么导致它表现出这种方式。
解决方法
我怀疑测试希望您在下面进行以下操作:
allowVolumeExpansion: true
我假设测试希望您覆盖构造函数本身中的属性,而不是显式设置
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。