【问题标题】:Initialising variable with getter in Constructor在构造函数中使用 getter 初始化变量
【发布时间】: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


【解决方案1】:

所有场景都给出相同的结果。

我使用了一个样本值作为方向 10

public class Car {
    int direction=10;
    public int getDirection(){
        return this.direction;
    }

    public static void main(String[] args) {
        Ecar e = new Ecar();
        e.print();
    }
}

class Ecar extends Car{

//    Case 1
//    int direction;
//    public Ecar(){
//        this.direction = getDirection();
//    }

//    case 2
//    int direction = this.getDirection();

//    case3
//    int direction = super.getDirection();

//    case 4
//    int direction = this.getDirection();

    public void print(){
        System.out.println(this.direction);
    }
}

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多