java static

2009-04-10 2:29 am
int a and static int a
佢地2個都系int
有咩分別

回答 (2)

2009-04-10 1:29 pm
✔ 最佳答案
佢地2個都系int
but int is accessible from within an instance
while static int is accessible from within an instance and from a static method.
It would be useful for example, if you want to accumulate results from all instances to make a total.
The following example shows how it works:
public class TestStatic
{
static int a=10;
int b=5;
public TestStatic(){a+=5;}
public static void main(String[] args)
{
TestStatic t;
System.out.println("static a="+a);
// System.out.println("static b="+b); compilation error
t=new TestStatic();
System.out.println("a="+t.a);
System.out.println("b="+t.b);
}
}
/* output
static a=10
a=15
b=5
Press any key to continue . . .
*/

2009-04-13 21:20:32 補充:
b is an instance variable which is accessible from an instance, i.e. an object instantiated from the class. It is therefore not visible from a static method (such as main). The compiler sees this and so flags it as a compiler error.

2009-04-13 21:23:49 補充:
Think of the static method as a father who has 4 sons (instances). He has a family purse (static variable) with money everybody can see (visible). But he cannot see the money (instance variable) in the pocket of each of his sons (instances).
2009-04-11 8:51 pm
int a 係一個instance variable
static int a 係一個class variable, 所有instances可以access


收錄日期: 2021-04-13 16:33:12
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090409000051KK01557

檢視 Wayback Machine 備份