окончательная инициализация переменной в производном классе - PullRequest
0 голосов
/ 21 ноября 2019

Я в замешательстве, если мы можем инициализировать последнюю переменную базового класса в его производном классе. Мой базовый класс -

    abstract class MyClass1 {
        //Compiler Error:Variable is not initialized in the default constructor.

        public final int finalVar;
    }
    //And my derived class with variable initialization.

    class DerivedClass extends MyClass1 {
        DerivedClass()
        {
            super();
            //Cannot asssign a value to finalVar.
            finalVar = 1000;
        }
   }

Скажите, пожалуйста, возможно ли инициализировать последнюю переменную в производном классе. Будет ли это просто ошибка времени компиляции или ошибка времени выполнения?

Ответы [ 3 ]

1 голос
/ 21 ноября 2019

Последняя переменная должна быть инициализирована в конструкторе, которого нет в вашем абстрактном классе. Добавление этого конструктора позволит вам вызвать его через super (). Рассмотрим следующий пример:

public class Main {
    public static void main(String[] args) {
        baseClass instance = new derivedClass(1);
    }
}

abstract class baseClass {
    protected final int finalVar;
    baseClass(int finalVar){
        this.finalVar = finalVar;
    }
}

class derivedClass extends baseClass {
    derivedClass(int finalVar){
        super(finalVar);
        System.out.println(this.finalVar);
    }
}
0 голосов
/ 21 ноября 2019

Заключительные члены должны быть инициализированы в конструкторе класса. Вы можете изменить свой код, чтобы подкласс передавал значение через конструктор:

abstract class MyClass1 {

    public final int finalVar;

    protected MyClass1(int var) {
         finalVar = var;
    }

} 

class DerivedClass extends MyClass1 {
    DerivedClass() {
        super(1000);
    }
}
0 голосов
/ 21 ноября 2019

Вы должны присвоить значение своей переменной в родительском классе.

// Declaring Parent class
class Parent {
    /* Creation of final variable pa of string type i.e 
    the value of this variable is fixed throughout all 
    the derived classes or not overidden*/
    final String pa = "Hello , We are in parent class variable";
}
// Declaring Child class by extending Parent class
class Child extends Parent {
    /* Creation of variable ch of string type i.e 
    the value of this variable is not fixed throughout all 
    the derived classes or overidden*/
    String ch = "Hello , We are in child class variable";
}

class Test {
    public static void main(String[] args) {
        // Creation of Parent class object
        Parent p = new Parent();
        // Calling a variable pa by parent object 
        System.out.println(p.pa);
        // Creation of Child class object
        Child c = new Child();

        // Calling a variable ch by Child object 
        System.out.println(c.ch);
        // Calling a variable pa by Child object 
        System.out.println(c.pa);
    }
}
...