在构造函数中用 getter 初始化变量
Initialising variable with getter in Constructor
如果我有一辆 class 车 getter 像这样:
public int getDirection(){
return this.direction;
}
和一个扩展汽车的 Subclass:
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();
所有场景给出相同的结果。
我使用了样本值 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);
}
}
如果我有一辆 class 车 getter 像这样:
public int getDirection(){
return this.direction;
}
和一个扩展汽车的 Subclass:
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();
所有场景给出相同的结果。
我使用了样本值 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);
}
}