[英]final variable initialization in derived class
如果我們可以在派生的 class 中初始化基礎 class 的最終變量,我會感到困惑。 我的基礎 class 是
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;
}
}
請告訴我是否可以在派生的 class 中初始化最終變量。 它只會給出編譯時錯誤還是運行時錯誤?
最終變量需要在構造函數中初始化,您的抽象 class 缺少該變量。 添加該構造函數然后允許您通過 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);
}
}
您必須為父 class 中的變量分配一個值。
// 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);
}
}
最終成員需要在 class 的構造函數中初始化。 您可以修改代碼以使子類通過構造函數傳遞值:
abstract class MyClass1 {
public final int finalVar;
protected MyClass1(int var) {
finalVar = var;
}
}
class DerivedClass extends MyClass1 {
DerivedClass() {
super(1000);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.