posts - 51, comments - 17, trackbacks - 0, articles - 9
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

java static

Posted on 2007-04-08 20:12 chenweicai 阅读(124) 评论(0)  编辑  收藏

1.静态变量

public class Chinese {

 static String country = "中国";
 
 String name;
 int age;
 
 void singOurCountry(){
  System.out.println("啊, 亲爱的" + country);
 }
}

 public static void main(String[] args) {

  System.out.println("Chinese country is :" + Chinese.country);//类.成员
  Chinese ch1 = new Chinese();
  System.out.println("Chinese country is :" + ch1.country);//对象.成员
        ch1.singOurCountry();
 }


注:1. 不能把任何方法内的变量声明为static类型
        2. 静态成员变量为该类的各个实例所共享,所以在内存中该变量只有一份,
            经常用来计数统计
如:
class A{
     private static int  count = 0;

      public A(){
          count = count + 1;  
    }

public void finalize(){//在垃圾回收时,finalize方法被调用
       count = count - 1;
    }
}


2.静态方法
public class Chinese {

 //在静态方法里,只能直接调用同类中的其他静态成员,不能直接访问类中的非静态成员和方法
 //因为对如非静态成员和方法,需先创建类的实例对象后才可使用。
 //静态方法不能使用关键字this和super,道理同上
 //main方法是静态方法,不能直接访问该类中的非静态成员,必须先创建该类的一个实例
 static void sing(){
  System.out.println("啊...");
 }
 
 void singOurCountry(){
  sing();//类中的成员方法可以直接访问静态成员方法
  System.out.println("啊...祖国...");
 }
}

 public static void main(String[] args) {

  Chinese.sing();//类.方法
  
  Chinese ch1 = new Chinese();
  ch1.sing();//对象名.方法
  ch1.singOurCountry();
 }


3. 静态代码块
public class StaticCode {

 static String country;
 
 static{
  country = "Chine";
  System.out.println("Static code is loading...");
 }
}

public class TestStatic {

 static{
  System.out.println("TestStatic code is loading..."); 
 }
 
 public static void main(String[] args){
  System.out.println("begin executing main method...");
  //类中的静态代码将会自动执行,尽管产生了类StaticCode的两个实例对象,
  //但其中的静态代码块只被执行了一次。同时也反过来说明:类是在第一次被使用时
  //才被加载,而不是在程序启动时就加载程序中所有可能要用到的类
  new StaticCode();
  new StaticCode();
 }
 
}




只有注册用户登录后才能发表评论。


网站导航: