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

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

静态方法 百度一下

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());
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值