Инициализация переменной с помощью геттера в конструкторе - PullRequest
0 голосов
/ 07 мая 2020

Если у меня есть класс Car с таким получателем:

public int getDirection(){
   return this.direction;
}

и подкласс, расширяющий car:

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();

1 Ответ

0 голосов
/ 07 мая 2020

Все сценарии ios дают одинаковый результат.

Я использовал примерное значение 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);
    }
}
...