我在網上MOOC學習有關構造函數創建時的構造,我有如下的原始代碼片段:錯誤Java的最後一個變量聲明爲其他變量
package com.example.accountapp.logic;
import com.example.accountapp.ui.OutputInterface;
/**
* This file defines the Account class. It provides the basis for a
* series of improvements you'll need to make as you progress through
* the lessons in Module 6.
*/
public class Account {
/**
* This is the variable that stores our OutputInterface instance.
* <p/>
* This is how we will interact with the User Interface
* [MainActivity.java].
* </p>
* This was renamed to 'mOut' from 'out', as it is in the video
* lessons, to better match Android/Java naming guidelines.
*/
final OutputInterface mOut;
/**
* Name of the account holder.
*/
String name;
/**
* Number of the account.
*/
int number;
/**
* Current balance in the account.
*/
double balance;
/**
* Constructor initializes the field
*/
public Account(OutputInterface out) {
mOut = out;
}
/**
* Deposit @a amount into the account.
*/
public void deposit(double amount) {
balance += amount;
}
/**
* Withdraw @a amount from the account. Prints "Insufficient
* Funds" if there's not enough money in the account.
*/
public void withdrawal(double amount) {
if (balance > amount)
balance -= amount;
else
mOut.println("Insufficient Funds");
}
/**
* Display the current @a amount in the account.
*/
public void displayBalance() {
mOut.println("The balance on account "
+ number
+ " is "
+ balance);
}
}
現在我需要將所有變量更改爲私有,併爲字段名稱,數字和餘額添加構造函數。
我創建如下兩個構造函數:
public Account(double newBalance){balance = newBalance;}
public Account(String newName, int newNumber, double newBalance){
this(newBalance);
name = newName;
number = newNumber;
}
添加這些構造導致錯誤的如下最終變量聲明:
MOUT的變量可能尚未初始化。
當我刪除我的兩個新的構造函數或從變量mOut中刪除final時,錯誤消失。
我可以知道爲什麼這個錯誤發生?我試着通過StackOverflow尋找答案,但無法找到類似的情況。謝謝。
這是因爲不是所有的構造函數將初始化'mOut'。 – Li357
如果有人調用其中一個新的構造函數,則不會設置「mOut」。有什麼不清楚的情況? –
我不知道爲什麼它不是那麼與其他變量(所有變量必須在每個構造函數聲明),但只有與類型決賽。 – yogescicak