1. 我们先来看看各种类型的属性初始化的默认值
public byte b;
public short s;
public char c ;
public int i ;
public float f;
public long l;
public double d;
public boolean flag ;
public InitDemo initDemo;
打印出来的结果是
0
0
0
0.0
0
0.0
false
null
char默认是’\u0000’,显示为空白,其它的都比较正常
2. 构造器初始化
下面是使用无参构造,获得对象的实例,
ParentClass parent = new ParentClass();
在无继承关系的对象中的普通属性、静态属性、静态代码块、普通代码块、构造函数,它们执行的顺序又是怎么样的呢?我们来看个示例
public class ParentClass {
private InitDemo parentInit1 = new InitDemo("ParentClass init1") ;
public static InitDemo parentInit2 = new InitDemo("ParentClass static init2") ;
{
InitDemo parentInit3 = new InitDemo("ParentClass code block init3") ;
}
static{
InitDemo parentInit4 = new InitDemo("ParentClass static code block init4") ;
}
private InitDemo parentInit5 = new InitDemo("ParentClass init5") ;
public static InitDemo parentInit6 = new InitDemo("ParentClass static init6") ;
public ParentClass() {
System.out.println("ParentClass constructor");
}
public static void main(String[] args) {
new ParentClass();
}
}
执行main方法,输出的结果
ParentClass static init2
ParentClass static code block init4
ParentClass static init6
ParentClass init1
ParentClass code block init3
ParentClass init5
ParentClass constructor
通过输出结果我们可以得到下面的结论,在无继承对象的初始化中
静态属性、静态代码块>普通属性、代码块>构造函数
静态属性、静态代码块的执行顺序按在代码中出现的顺序
普通属性、代码块的执行顺序按在代码中出现的顺序
那存在继承关系的初始化顺序呢
public class SubClass extends ParentClass{
private InitDemo init1 = new InitDemo(" SubClass init1") ;
public static InitDemo init2 = new InitDemo("SubClass static init2") ;
{
InitDemo init3 = new InitDemo("SubClass code block init3") ;
}
static{
InitDemo init4 = new InitDemo("SubClass static code block init4") ;
}
private InitDemo init5 = new InitDemo("SubClass init5") ;
public static InitDemo init6 = new InitDemo("SubClass static init6") ;
public SubClass() {
System.out.println("SubClass constructor");
}
public static void main(String[] args) {
new SubClass();
}
}
执行main函数,输出的结果
ParentClass static init2
ParentClass static code block init4
ParentClass static init6
SubClass static init2
SubClass static code block init4
SubClass static init6
ParentClass init1
ParentClass code block init3
ParentClass init5
ParentClass constructor
SubClass init1
SubClass code block init3
SubClass init5
SubClass constructor
通过输出结果我们可以得到下面的结论,在存在继承关系对象的初始化中
父类静态属性、父类静态代码块>子类静态属性、子类静态代码块>父类普通属性、父类代码块>父类构造函数>子类普通属性、子类代码块>子类构造函数
静态属性、静态代码块的执行顺序按在代码中出现的顺序
普通属性、代码块的执行顺序按在代码中出现的顺序
静态属性也会被称为类属性,这是为什么呢?其实类本来也是一个对象,是一个Class对象,而我们说的静态属性、静态代码,静态方法都属于类对象,该类对象的每个实例对象都共享这个类对象。当你new一个对象实例的时候,这个类的Class对象已经初始化好了,Class对象就好比汽车这个抽象概念的信息集合,而类的实例对象就好比一辆奥迪A4L是汽车的具体存在。类是实例对象的抽象 实例对象是类的具体存在,