• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

通过代码实例解析JAVA类生命周期

java 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

代码

public class TestClass {

  public static int k=0;

  public static TestClass t1=new TestClass("t1");
  public static TestClass t2=new TestClass("t2");

  public static int i=print("i");

  public static int n=99;

  public int j=print("j");

  {
    print("构造块");
  }

  static {
    print("静态块");
  }

  public TestClass(String str) {
    System.out.println((++k)+""+str+"i="+i+"n="+n);
    ++n;
    ++i;
  }

  public static int print(String str){
    System.out.println((++k) +":" + str + "  i=" + i + "  <div style="color:transparent">本文来源gaodai.ma#com搞##代!^码@网*</div>n=" + n);
    ++n;
    return ++ i;
  }

  public static void main(String[] args){
    System.out.println("=========start============");
    TestClass t = new TestClass("init");
    System.out.println("=========end============");
  }
}

执行结果

1:j  i=0  n=0
2:构造块  i=1  n=1
3t1i=2n=2
4:j  i=3  n=3
5:构造块  i=4  n=4
6t2i=5n=5
7:i  i=6  n=6
8:静态块  i=7  n=99
=========start============
9:j  i=8  n=100
10:构造块  i=9  n=101
11initi=10n=102
=========end============

讲解

代码由上到下 依次执行

由static修饰的变量或方法是在方法区,属于类变量、类方法

new对象这个操作,new出来的对象在堆里 对象的引用在栈里

new出来的对象 方法快先构造方法执行

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:通过代码实例解析JAVA类生命周期
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址