构造方法是静态的吗?

public class Test  {
	private int k = printInit("Beetle.k initialized");
    int j;
    
	public Test() {
		System.out.println("k = " + k);
		System.out.println("j = " + j);
	}

	private static int x2 = printInit("static Beetle.x2 initialized");
	
	static int printInit(String s) {
		System.out.println(s);
		return 47;
	}

	public static void main(String[] args) {
		System.out.println("Beetle constructor");
		new Test();
	}
}

 结果:

static Beetle.x2 initialized
Beetle constructor
Beetle.k initialized
k = 47
j = 0

 

可见访问构造方法时同时也执行了静态初始化,根据《Thinking in Java 4》,类加载和静态成员初始化是等价的,而类加载的触发条件几乎就是but loading also occurs when a static field or static method is accessed.

由此得出:构造方法就是static method了。

 

另一例:

public class Test1 {
	static {
		RuntimeException ex = new RuntimeException();
		ex.fillInStackTrace();
		ex.printStackTrace();
	}

	public Test1() {
		throw new RuntimeException();
	}

	public static void main(String[] args) throws Exception {
		new Test1();
	}
}

 结果:

java.lang.RuntimeException
    at Test1.<clinit>(Test1.java:4)
Exception in thread "main" java.lang.RuntimeException
    at Test1.<init>(Test1.java:9)
    at Test1.main(Test1.java:13)

 

以上Test1.<init>是发生在 throw new RuntimeException(); 一行,但不清楚实质是否如形式所标示的那样类似一个init静态方法调用,还是暗藏对象对init方法的调用?

 

因为再看:

public class Test1 {
	static {
		RuntimeException ex = new RuntimeException();
		ex.fillInStackTrace();
		ex.printStackTrace();
	}

	public Test1() {
		//throw new RuntimeException();
	}
	
	public void hello() {
		throw new RuntimeException();
	}

	public static void main(String[] args) throws Exception {
		Test1 t = new Test1();
		t.hello();
	}
}
 

结果:

java.lang.RuntimeException
    at Test1.<clinit>(Test1.java:4)
Exception in thread "main" java.lang.RuntimeException
    at Test1.hello(Test1.java:13)
    at Test1.main(Test1.java:18)

非静态方法hello抛异常的表示形式也是如此 类名.方法名

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值