java - 如何覆盖子类中超类的属性?
问题描述
我很确定我的代码应该可以正常工作,但是我的学习平台中的测试失败了,说明我的子类中的构造函数“应该将描述设置为‘未分类’以外的值”
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");
}
我假设测试希望您覆盖构造函数本身中的属性,而不是显式设置它
推荐阅读
- libc - 意外重命名 libc.so.6 并且无法在救援模式下 chroot
- android-studio - 升级我的 Android SDK 后出现“错误:无法访问 FragmentActivity”
- javascript - 如何中止调用的ajax方法c#.net
- delphi - Delphi - 快速报告(动态报告预览)
- sql - 显示耗时最长的任务 sql
- r - 当 n = 1 时,为什么 TTR::SMA 为系列的第一个元素返回 NA?
- eclipse-emf - 如何在 ContainerShape Graphiti 中添加组合功能
- android - 配置项目“:react-native-vector-icons”时出现问题
- c# - 为 RSACryptoProvider 和 BouncyCastle 生成密钥/加密/解密
- javers - 自动忽略@OneToMany、@ManyToOne