2013-06-02 27 views
0

我很難過。我想通過包含getters和setter來優化一些代碼。這是我到目前爲止有:得到並設置在Java類

public class ThingHolder { 
private int updateCounter=0; 
private Object theThing; 

public Object getThing() { 
    return theThing; 
} 

public void setThing(Object theThing) { 
    this.theThing = theThing; 
    updateCounter++; 
} 

public int getUpdateCounter() { 
    return updateCounter; 
} 

和:

public class ThingHolderTester { 
public static void main(String[] args) { 
    ThingHolder t = new ThingHolder(); 

    t.setThing="First Object"; t.updateCounter++; 
    System.out.println("The thing is currently " + t.getThing + " and the ThingHolder has been updated " + t.updateCounter + " times"); 

    t.setThing="Second Object"; t.updateCounter++; 
    System.out.println("The thing is currently " + t.getThing + " and the ThingHolder has been updated " + t.updateCounter + "times"); 
} 

此刻,我不斷收到錯誤無法找到我的get和set方法的象徵。請幫忙嗎?

回答

1

你的代碼更改爲:

public class ThingHolderTester { 
public static void main(String[] args) { 
    ThingHolder t = new ThingHolder(); 

    t.setThing("First Object"); 
    System.out.println("The thing is currently " + t.getThing() + " and the ThingHolder has been updated " + t.getUpdateCounter() + " times"); 

    t.setThing("Second Object"); 
    System.out.println("The thing is currently " + t.getThing() + " and the ThingHolder has been updated " + t.getUpdateCounter() + "times"); 
} 

問題:

  1. 要叫你需要添加一個功能 「()」 和中添加必需的參數。
  2. setThing方法更新計數器本身,無需手動在主代碼中執行。
  3. updateCounter屬性是私有的,不能直接被其他類訪問。
+0

非常感謝你! – germantom

1

這些是函數

要使用的功能,你需要呼叫它,使用括號。

+0

謝謝,我該如何將Thing設置爲「First Object」的值?我仍然無法找到符號,當我嘗試t.setThing =「第一個對象」; – germantom

+0

@germantom:通過**調用**函數,帶參數。 – SLaks

0
t.setThing="First Object"; t.updateCounter++; 

其他錯誤:你會數數兩次!

第一次調用.setThing,第二次調用t.updateCounter。

0

創建類時,您可以使用可以插入到netbeans或eclipse中的get和set(插入代碼 - > getter和setter)。然後調用主函數中的這些函數來創建所創建類的新實例。