【发布时间】:2020-05-07 15:02:03
【问题描述】:
如果我有一个带有像这样的吸气剂的 Car 类:
public int getDirection(){
return this.direction;
}
还有一个扩展汽车的子类:
public class Ecar extends Car{
}
如果我按照下面的例子初始化值方向有没有区别:
1)
int direction;
public Ecar(){
this.direction = getDirection();
}
2)
public Ecar(){...}
int direction = getDirection();
3)
int direction = super.getDirection();
4)
int direction = this.getDirection();
【问题讨论】:
-
你意识到当你做
this.direction = getDirection()时,就像在做this.direction = this.direction,对吧?您需要将direction作为参数传递给构造函数 -
@user 但 getDirection 来自上层阶级。那么如果我在子类中调用 getDirection,不应该将上类的值分配给 this.direction 吗?
-
如果你已经在超类中有一个方向字段,为什么要在
Ecar中隐藏它?此外,在您的构造函数中,方向字段将为空 -
@user 如果满足条件,我将在子类中覆盖它。
-
然后在
Car中创建一个setter。无论如何,direction尚未在构造函数中设置。这种重复可能只会给你带来麻烦
标签: java parameters constructor getter