2017-04-12 24 views
-2

我在网上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寻找答案,但无法找到类似的情况。谢谢。

+1

这是因为不是所有的构造函数将初始化'mOut'。 – Li357

+1

如果有人调用其中一个新的构造函数,则不会设置“mOut”。有什么不清楚的情况? –

+0

我不知道为什么它不是那么与其他变量(所有变量必须在每个构造函数声明),但只有与类型决赛。 – yogescicak

回答

1

由于变量声明为final因此,他们必须创建对象本身期间initilized。稍后,您不应该修改声明为final的引用来引用任何其他对象(或任何其他基本变量的值)。因此,您需要初始化所有构造函数中的所有最终变量。当你定义你的构造函数时,如果你有2个构造函数(重载)意味着你有两种方法来创建你的对象。在这种情况下,每种方法都必须初始化最终变量。

编辑注意变量定义为final不保证不可变性。它只是你不能重新分配他们(使用=),他们可以而且必须只能(在声明本身的时间在你的情况在所有的构造函数,在局部变量的情况下),一旦initilized。当然,你仍然可以使用.(点运算符),并且如果有任何mutator方法可以调用它们。

+0

谢谢,非常清楚的解释。我并不知道最终变量的这种行为。 – yogescicak

0

对于最终变量mOut,每当创建对象时它都应该有一个值。

中的其他构造函数的默认值初始化MOUT你想

参见:How final keyword works

0

在java中你必须initiliaze在声明或构造函数中最后一个变量。 如果最终变量未初始化的声明yyou不能创建构造函数不初始化。