1 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
問(wèn)題出在以下幾行
public class Two
{
One database;
public Two()
{
One database = new One();
//this variable is not the same as the one declared outside the constructor
}
當(dāng)在方法中聲明與類中聲明的變量同名的變量時(shí),在方法內(nèi)聲明的變量上發(fā)生的修改不會(huì)在方法外的變量中看到(因?yàn)閮蓚€(gè)變量不同)。方法中的變量正在隱藏類中的變量。要區(qū)分這兩個(gè)變量,您必須使用this關(guān)鍵字
this.database = new One();
最終解決方案應(yīng)該是
public class Two
{
One database;
public Two()
{
this.database = new One();
}
執(zhí)行database.addElement(name);時(shí)出現(xiàn)NullPointerException的原因;是因?yàn)樵谀氖纠?,?shù)據(jù)庫(kù)未實(shí)例化,因?yàn)閯?chuàng)建的對(duì)象存儲(chǔ)在另一個(gè)名為database 的變量中,而不是聲明為類屬性的變量中。
添加回答
舉報(bào)