2013-07-15 31 views
1

我最近遇到了這句話:類成員的定義在java中

"Class A has class member int a" 

可能明顯但這句話只是意味着aclass A定義的int,對不對?

另一件事,例如a定義在class A的方法下。它是否仍然是 的一名班員?
我還沒有找到類成員的明確定義,我看了here: 但它不是很有幫助。

感謝的提前幫助

回答

6

類成員調用靜態成員的另一種方式。

class A { 
    int a; //instance variable 
    static int b; //class variable 
    public void c() { 
     int d; //local variable 
    } 
} 
+1

Jinx!但是你已經完成了很好的代碼示例。 :-) –

+0

b在所有情況下都是一樣的,但是a是不同的,有時d有時不存在? –

+0

好吧,所以基本上我的例子他們說類A與int靜態? – Octo

1

In same docs

字段在他們的聲明中static修飾符在

稱爲

類變量是由類名本身引用靜態字段或類變量,如

Bicycle.numberOfBicycles 

這表明它們是類變量。

1

類成員不僅僅是類的變量。他們可以使用類名來訪問。這意味着它們是該類的靜態變量。

該文件明確提到它。

public class Bicycle { 

private int cadence; 
private int gear; 
private int speed; 

// add an instance variable for the object ID 
private int id; 

// add a class variable for the 
// number of Bicycle objects instantiated 
private static int numberOfBicycles = 0; 

... 
} 

在上面的代碼numberOfBicycles是一個類成員。它可以使用

Bicycle.numberOfBicycles 

方法內的變量不能像這樣訪問。所以他們不能成爲班級成員。在方法中聲明的變量是局部變量,屬於該方法。所以你可以稱他們爲最終的,但不是靜態的或公共的,或保護或私人的。

0

link你mentiond的文檔,其在第一線清晰(抽穗後),其

In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class. 

因此,這意味着static關鍵字用來創建類字段和方法(i.e.class成員)。 所以你的情況,

class A{ 
    int a; 
    public void methodA(){ 
     int a;//inner a 
    } 

} 

什麼你問的是,是int a裏面了methodA()仍然是一個類成員?

答案是no:因爲它沒有在static關鍵字之前。如果您嘗試使用static關鍵字爲:

class A{ 
    int a; 
    public void methodA(){ 
     static int a;//inner a will cause compile time error 
    } 

} 

你會得到編譯時錯誤。 希望幫助! :)