【发布时间】:2020-11-09 02:55:21
【问题描述】:
我很确定我的代码应该可以正常工作,但是我的学习平台中的测试失败了,说明我的子类中的构造函数“应该将描述设置为 '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
避免该问题的一种方法是将父类中的描述设置为“”而不是“未分类”,但需要将其设置为“未分类”。
我不知道是什么导致了它的行为。
【问题讨论】:
-
我猜失败表明
SedimentaryRock构造函数应该设置描述,例如,而不是测试代码。同样在您的实现中,覆盖 setter/getter 是没有用的。
标签: java inheritance computer-science