ºìÁªLinuxÃÅ»§
Linux°ïÖú

Àí½âstatic

·¢²¼Ê±¼ä:2006-05-03 14:45:14À´Ô´:ºìÁª×÷Õß:reing
ÓÐʱÄãÏ£Íû¶¨ÒåÒ»¸öÀà³ÉÔ±£¬Ê¹ËüµÄʹÓÃÍêÈ«¶ÀÁ¢ÓÚ¸ÃÀàµÄÈκζÔÏó¡£Í¨³£Çé¿öÏ£¬Àà³ÉÔ±±ØÐëͨ¹ýËüµÄÀàµÄ¶ÔÏó·ÃÎÊ£¬µ«ÊÇ¿ÉÒÔ´´½¨ÕâÑùÒ»¸ö³ÉÔ±£¬ËüÄܹ»±»Ëü×Ô¼ºÊ¹Ó㬶ø²»±ØÒýÓÃÌض¨µÄʵÀý¡£ÔÚ³ÉÔ±µÄÉùÃ÷Ç°Ãæ¼ÓÉϹؼü×Östatic(¾²Ì¬µÄ)¾ÍÄÜ´´½¨ÕâÑùµÄ³ÉÔ±¡£Èç¹ûÒ»¸ö³ÉÔ±±»ÉùÃ÷Ϊstatic£¬Ëü¾ÍÄܹ»ÔÚËüµÄÀàµÄÈκζÔÏó´´½¨Ö®Ç°±»·ÃÎÊ£¬¶ø²»±ØÒýÓÃÈκζÔÏó¡£Äã¿ÉÒÔ½«·½·¨ºÍ±äÁ¿¶¼ÉùÃ÷Ϊstatic¡£static ³ÉÔ±µÄ×î³£¼ûµÄÀý×ÓÊÇmain( ) ¡£ÒòΪÔÚ³ÌÐò¿ªÊ¼Ö´ÐÐʱ±ØÐëµ÷ÓÃmain() £¬ËùÒÔËü±»ÉùÃ÷Ϊstatic¡£

ÉùÃ÷ΪstaticµÄ±äÁ¿ÊµÖÊÉϾÍÊÇÈ«¾Ö±äÁ¿¡£µ±ÉùÃ÷Ò»¸ö¶ÔÏóʱ£¬²¢²»²úÉústatic±äÁ¿µÄ¿½±´£¬¶øÊǸÃÀàËùÓеÄʵÀý±äÁ¿¹²ÓÃͬһ¸östatic±äÁ¿¡£ÉùÃ÷ΪstaticµÄ·½·¨ÓÐÒÔϼ¸ÌõÏÞÖÆ£º

?
ËüÃǽöÄܵ÷ÓÃÆäËûµÄstatic ·½·¨¡£
?
ËüÃÇÖ»ÄÜ·ÃÎÊstaticÊý¾Ý¡£
?
ËüÃDz»ÄÜÒÔÈκη½Ê½ÒýÓÃthis »òsuper£¨¹Ø¼ü×Ösuper Óë¼Ì³ÐÓйأ¬ÔÚÏÂÒ»ÕÂÖÐÃèÊö£©¡£
Èç¹ûÄãÐèҪͨ¹ý¼ÆËãÀ´³õʼ»¯ÄãµÄstatic±äÁ¿£¬Äã¿ÉÒÔÉùÃ÷Ò»¸östatic¿é£¬Static ¿é½öÔÚ¸ÃÀà±»¼ÓÔØʱִÐÐÒ»´Î¡£ÏÂÃæµÄÀý×ÓÏÔʾµÄÀàÓÐÒ»¸östatic·½·¨£¬Ò»Ð©static±äÁ¿£¬ÒÔ¼°Ò»¸östatic ³õʼ»¯¿é£º

// Demonstrate static variables£¬methods£¬and blocks.

class UseStatic {
static int a = 3;
static int b;

static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);

}

static {
System.out.println("Static block initialized.");
b = a * 4;

}

public static void main(String args[]) {
meth(42);
}
}

Ò»µ©UseStatic Àà±»×°ÔØ£¬ËùÓеÄstaticÓï¾ä±»ÔËÐС£Ê×ÏÈ£¬a±»ÉèÖÃΪ3£¬½Ó×Åstatic ¿éÖ´ÐÐ(´òÓ¡Ò»ÌõÏûÏ¢)£¬×îºó£¬b±»³õʼ»¯Îªa*4 »ò12¡£È»ºóµ÷ÓÃmain()£¬main() µ÷ÓÃmeth() £¬°ÑÖµ42´«µÝ¸øx¡£3¸öprintln ( ) Óï¾äÒýÓÃÁ½¸östatic±äÁ¿aºÍb£¬ÒÔ¼°¾Ö²¿±äÁ¿x ¡£

×¢Ò⣺ÔÚÒ»¸östatic ·½·¨ÖÐÒýÓÃÈκÎʵÀý±äÁ¿¶¼ÊÇ·Ç·¨µÄ¡£

ÏÂÃæÊǸóÌÐòµÄÊä³ö£º

Static block initialized.
x = 42
a = 3
b = 12
ÔÚ¶¨ÒåËüÃǵÄÀàµÄÍâÃ棬static ·½·¨ºÍ±äÁ¿ÄܶÀÁ¢ÓÚÈκζÔÏó¶ø±»Ê¹Óá£ÕâÑù£¬ÄãÖ»ÒªÔÚÀàµÄÃû×ÖºóÃæ¼ÓµãºÅÔËËã·û¼´¿É¡£ÀýÈ磬Èç¹ûÄãÏ£Íû´ÓÀàÍâÃæµ÷ÓÃÒ»¸östatic·½·¨£¬Äã¿ÉÒÔʹÓÃÏÂÃæͨÓõĸñʽ£º

classname.method( )

ÕâÀclassname ÊÇÀàµÄÃû×Ö£¬ÔÚ¸ÃÀàÖж¨Òåstatic·½·¨¡£¿ÉÒÔ¿´µ½£¬ÕâÖÖ¸ñʽÓëͨ¹ý¶ÔÏóÒýÓñäÁ¿µ÷Ó÷Çstatic·½·¨µÄ¸ñʽÀàËÆ¡£Ò»¸östatic±äÁ¿¿ÉÒÔÒÔͬÑùµÄ¸ñʽÀ´·ÃÎÊ----ÀàÃû¼ÓµãºÅÔËËã·û¡£Õâ¾ÍÊÇJava ÈçºÎʵÏÖÈ«¾Ö¹¦ÄܺÍÈ«¾Ö±äÁ¿µÄÒ»¸ö¿ØÖÆ°æ±¾¡£

ÏÂÃæÊÇÒ»¸öÀý×Ó¡£ÔÚmain() ÖУ¬static·½·¨callme() ºÍstatic ±äÁ¿bÔÚËüÃǵÄÀàÖ®Íâ±»·ÃÎÊ¡£

class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {

System.out.println("a = " + a);
}
}

class StaticByName {

public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);

}
}

ÏÂÃæÊǸóÌÐòµÄÊä³ö£º

a = 42
b = 99
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 0 ÌõÆÀÂÛ