讲讲类的实例化顺序,比如父类静态数据,构造函数,字段,子类静态数据,构造函数,字段,当 new 的时候,他们的执行顺序。
先说结论,顺序为:
代码举例说明: A.java
public class A {
int a1 = 8;
static int a3 = getA3();
int a2 = getA2();
{
int a3 = 9;
System.out.println("top of A() a1=" + a1 + " a2=" + a2 + " a3=" + a3);
}
public A() {
this(66);
System.out.print("A 构造函数\n");
}
{
System.out.println("below A()..has start");
}
public A(int num) {
System.out.print("A 带参数构造函数: " + num + "\n");
}
static {
System.out.println("I`m a static {} from class A..");
}
int getA2() {
System.out.println("getA2..");
return 7;
}
static int getA3() {
System.out.println("getA3..");
return 7;
}
public void methodA() {
System.out.println("methodA");
}
}
B.java
public class B extends A {
int b1 = 0;
int b2 = getB2();
static int b3 = getB3();
{
int b3 = 5;
System.out.println("top of B() b1=" + b1 + " b2=" + b2 + " b3=" + b3);
}
public B() {
this(33);
// super(44);//添加super语句,会导致实例化时直接执行父类带参数的构造函数
System.out.print("B 构造函数\n");
}
public B(int num) {
// 添加super语句,会导致实例化时直接执行父类带参数的构造函数
// 前提是带参数的构造函数B会被运行(new实例化或this)
// super(77);
System.out.print("B 带参数构造函数:" + num + "\n");
}
{
System.out.println("below B()..has start");
}
static {
System.out.println("I`m a static {} from class B..");
}
int getB2() {
System.out.println("getB2..");
return 33;
}
static int getB3() {
System.out.println("getB3..");
return 7;
}
@Override
public void methodA() {
System.out.println("methoaA int class B");
super.methodA();
}
}
mymain.java
public class mymain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main app run..");
B b = new B();
// B b = new B(22);
b.methodA();
}
}
综合结论,一个类的实例化过程:
Copyright: 采用 知识共享署名4.0 国际许可协议进行许可 Links: https://lixj.fun/archives/java基础-类的实例化顺序
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有