您的位置:首页 > 编程语言 > Java开发

JAVA静态代码块,静态方法,非静态方法 简单比较!~

2007-06-08 16:38 281 查看
静态代码块不包含在任何方法体中,当类被载入时自动执行静态代码块,且只被执行一次经,常用于类属性的初始化

静态方法 百度一下

StaticCode 方法如下

package org.dalong.staticblockcode;

/**
* @author HuangDaLong
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class StaticCode {
protected static String teststring;

static {
System.out.println("call staticcode successful!");
System.out.println("This is teststring: "+teststring );
}

protected static void staticMetho(){
System.out.println("hello,This is Static metho!");
teststring="Static metho made this string!";
}

public String getTeststring() {
return teststring;
}

public void setTeststring(String teststring) {
this.teststring = teststring;
}
}

测试方法如下,大家可以比较一下输出的结果;

package org.dalong.staticblockcode;

/**
* @author HuangDaLong
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class StaticCodeTest {
public static void main(String args[]) {
/**
* print:call staticcode successful!
* This is tststring:null
*/
new StaticCode();
/**
* no print;
*/
new StaticCode();
/**
* no print;
*/
StaticCode sc = new StaticCode();
/**
* print: null
*/
System.out.println(sc.getTeststring());
/**
* print: hello test;
*/
sc.setTeststring("hello,test!");
System.out.println(sc.getTeststring());
/**
* print:hello,This is Static metho!
*/
StaticCode.staticMetho();
/**
* print:Static metho made this string!
*/
System.out.println(sc.getTeststring());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐