2016-01-20 77 views
-5

我有一個關於引用變量的問題。java中的引用變量

我知道聲明一個引用變量不會創建該對象。

但在Android的,如果我寫:

Button button; 

//button.(methods are seen) 

button=(Button)findViewById(R.id.button1); //Does this instantiate the object? 

//button.(methods are seen) 

我怎麼能夠訪問Button類的方法,而沒有在任的首次明確創建對象和第二註釋行?

例如,我可以這樣做:

button.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View view) { 
     finish(); 
    } 
}); 

我不明白它是如何工作的。

+0

'(Button)findViewById(R.id.button1)'這裏引用對象並且不創建。 沒有引用或創建對象如何訪問對象的功能?這是編程基礎的重要部分。 – zIronManBox

+0

該代碼不會編譯!你甚至嘗試過嗎? – RAnders00

回答

2

當您在xml中使用<Button></Button>時,您正在創建一個Button對象(android會爲您創建它)。當您使用方法findViewById時,您正在獲取對創建的Button的引用。所以你可以訪問Button類的公共方法。

+0

非常感謝你 – erhan

+0

你的歡迎。 但我認爲你不應該在這裏問這種類型的問題。嘗試使用Google搜索之前問在stackoverflow。 :) –

+0

你說,當你使用findViewById你正在獲取一個創建的引用Button是引用存儲在按鈕變量? – erhan