【发布时间】:2022-06-11 01:03:00
【问题描述】:
有人可以解释为什么当我调用具有浮点类型的父类的 getter 时返回为 0?我很确定它与这种数据类型有关, 谢谢。
父类
public class BuildingForRent {
private int buildingDimensions;
private float advanceAmount;
public BuildingForRent(int buildingDimensions){
this.buildingDimensions=buildingDimensions;
}
public float getAdvanceAmount(){
return this.advanceAmount;
}
public void setAdvanceAmount(float advanceAmount){
this.advanceAmount = advanceAmount;
}
public int getBuildingDimensions(){
return this.buildingDimensions;
}
public void calculateAdvanceAmount(){
float advanceAmount = -1.0f;
if(this.buildingDimensions>0){
advanceAmount=this.buildingDimensions*10;
}
this.advanceAmount=advanceAmount;
}
@Override
public String toString() {
return "BuildingForRent (buildingDimensions=" + this.buildingDimensions
+ ")";
}
}
儿童班
public class ShopForRent extends BuildingForRent{
char shopType;
public ShopForRent(int buildingDimensions,char shopType){
super(buildingDimensions);
this.shopType=shopType;
}
public int identifyShopRent(){
int shopRent = 0;
switch(this.shopType) {
case 'A':
shopRent = 45000;
break;
case 'B':
shopRent = 30000;
break;
case 'C':
shopRent = 25000;
break;
default:
shopRent = -1;
}
return shopRent;
}
@Override
public void calculateAdvanceAmount(){
// float basicAmount = this.getAdvanceAmount();//why this is 0 ??
float basicAmount = this.getBuildingDimensions() * 10;
if(this.identifyShopRent() == -1.0f || basicAmount == -1.0f) {
this.setAdvanceAmount(-1.0f);
}
this.setAdvanceAmount(basicAmount + this.identifyShopRent());
}
@Override
public String toString() {
return "ShopForRent (BuildingForRent (buildingDimensions=" + this.getBuildingDimensions()
+ ")shopType=" + this.shopType + ")";
}
}
如您所见,我正在使用类对象调用父 getter,该 getter 正在使用 calculateAmount 函数设置,但是当我从子级调用它时,我无法返回正确的值。
【问题讨论】:
-
你期望它是什么?您调用
setAdvanceAmount的唯一位置是稍后在同一个函数中,那么您什么时候认为advanceAmount实例变量设置为非零值?
标签: java inheritance types