RSS
热门关键字:  jsp信息管理  jsp  学生管理  孙鑫  西門掃雪
当前位置 :| 首页>新手入门>基础知识>

static在java中的使用

来源:www.javaif.com 作者:Java世界 时间:2008-03-02 Tag: 点击:

static用法 还有一个值得探讨的例子:

//static最常见的方法就是main()方法,public static void main(String args[]){}
class test{
    
int i;
    
public test(){
        System.out.println(
"start:");
    }

}

class test1{
    System.out.println(
"pass:");//测试语句
    public static void main(String args[]){
        test t 
= new test();
        System.out.println(
"open:");//程序运行类,首先运行静态方法.所以在主类中main()方法首先运行,
//这就是,在类中static方法最先被运行.
    }

}

 

public class StaticInit
{
   
static int i;
   
int a;
   
public StaticInit()
   
{
      a
=6;
      System.out.println(
"a 的初始化"+a);
   }
 
   
public static void main(String[] args)
  
{
    
new StaticInit();
  }

  
static 
  
{
     i
=5;
     System.out.println(
"i 的初始化"+i);
  }

}

//我的思考是类应该先运行static方法,这个例子中static方法有 :
//static int i;
/* public static void main(String[] args)
  {
    new StaticInit();
  }
*/

/*static 
  {
     i=5;
     System.out.println("i 的初始化"+i);
  }
*/

//先运行静态方法,应该按顺序运行
// static int i;静态成员 ->  静态块 -> 然后再运行非静态成员 最后再运行 构造函数(一般系统默认运行不带参数的构造函数);

 

在有继承关系的例子中:

也是运用这种规则

 下面例子中用到 静态成员、静态块、成员、构造函数等,以下程序未经测试,程序结果是我认为的正确结果!

 

class test{
    
static int i = 1;//对i 赋值
    
public f(){
        System.out.println(
"test-f"+i);
    }

    System.out.println(
"test-c"+i);
    
public test(){
         System.out.println(
"test"+i);
    }

    
static{
        i 
= 4;//再次赋值,覆盖原值
        System.out.println(
"test-static"+i);
    }

}

class test1 extends test{//继承test方法
     System.out.println(
"test1-first");
     
static int n = 2;//对n赋值
     System.out.println(
"test1--second"+n);
     
public test1(){
          System.out.println(
"test1-three");
     }

     
public static main(String args[]){
         test1 t 
= new test1();
         t.f();//调用父类方法
     }

     
static{
        n
=3;//再次赋值,覆盖原值
        System.out.println(
"test1-static-first"+n);
     }

}

//预计结果:
//test1-static-first3
//test-static4
//test-c4
//test4
//test1-first
//test1--second3
    //test1-three
//test-f4

 首先运行继承类的static函数 static int n = 2;但是紧接着static块又为n赋值,又因为n为静态所以n值永远为3

然后运行main()函数,出现new()方法,因为是继承类 初始化父类,i 赋值  与n原理相同所以 ii输出永远为4,

父类 初始化同样按照 static -> 非static -> 构造函数,初始化子类,因为子类static部分已经初始化,所以直接

非static -> 构造函数 ->继续运行main()中方法。


上一篇:用tomcat使用连接池连接到MSSQL
下一篇:没有了
最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册
热门焦点
精彩推荐