初始化
目录
- static关键字
- static与对象无关
- main()方法是static方法是程序的入口
- 非static不能调用static
- 创建对象的过程
static关键字
- 为什么使用static?
- java源代码虽然都是由类组成,表面上每个类都是平等的。那到底要先执行哪个类的代码呢?答案是类名与文件名相同的类。如是实现?此类有main()方法而main方法声明为static
创建对象的过程
- 无继承的普通类
- 加载类
- 此时要初始化类中static属性
- 实例化对象
- 初始化普通属性
- 调用构造方法
- 加载类
- 有继承的普通类
- 由上至下加载类
- 初始化static属性
- 由上至下实例化对象
- 初始化普通属性
- 调用构造方法
- 由上至下加载类
class A{
public A(int i) {
System.out.println(i);
}
}
class B{
private static A sta1 = new A(1);
private A sta2 = new A(2);
public B() {
System.out.println("B");
}
}
class C extends B{
private static A sta3 = new A(3);
private A sta4 = new A(4);
public C() {
System.out.println("C");
}
}
public class InitTest{
private static A sta5 = new A(5);
private A sta6 = new A(6);
public static void main(String[] args) {
C c = new C();
}
}
/*Output:
5
1
3
2
B
4
C
*/
class A{
public A(int i) {
System.out.println(i);
}
}
class B{
private static A sta1 = new A(1);
private A sta2 = new A(2);
public B() {
System.out.println("B");
}
}
class C extends B{
private static A sta3 = new A(3);
private A sta4 = new A(4);
public C() {
System.out.println("C");
}
}
public class InitTest extends C{
private static A sta5 = new A(5);
private A sta6 = new A(6);
public static void main(String[] args) {
InitTest it = new InitTest();
}
}
/*Output:
1
3
5
2
B
4
C
6
*/
Three passions, simple but overwhelmingly strong, have governed my life: the longing for love, the search for knowledge, and unbearable pity for the suffering of mankind