Java总结(二)——初始化与访问权限

一、初始化

1.类的初始化顺序

先看例子,后面说明结论:
class Window{
	public Window(int marker){
		System.out.println("Window " + marker);
	}
}
class House{
	Window w1 = new Window(1);
	public House(){
		System.out.println("House()");
		w3 = new Window(33);
	}
	Window w2 = new Window(2);
	Window w3 = new Window(3);
	
	public static void main(){
		House h = new House();
	}
	
}
执行结果是什么?
答案:
Window 1
Window 2
Window 3
House()
Window 33

结论:先进行类成员的初始化,之后调用构造函数。即使成员变量的定义分布在各个方法之间。


2.静态成员的初始化

例子:
class Bowl{
	public Bowl(int marker){
		System.out.println("Bowl " + marker);
	}
}
class Table{
	static Bowl bowl1 = new Bowl(1);
	public Table(){
		System.out.println("Table()");
	}
	static Bowl bow2 = new Bowl(2);
}
class Cupboard{
	Bowl bowl3 = new Bowl(3);
	static Bowl bowl4 = new Bowl(4);
	public Cupboard(){
		System.out.println("Cupboard()");
	}
	static Bowl bowl5 = new Bowl(5);
}
class StaticInitTest{
	public static void main(String[] args){
		System.out.println("Cupboard() running in main");
		new Cupboard();
	}
	static Table table = new Table();
	static Cupboard cupboard = new Cupboard();
}
执行结果是什么?
答案:
Bowl 1
Bowl 2
Table()
Bowl 4
Bowl 5
Bowl 3
Cupboard()
Cupboard() running in main
Bowl 3
Cupboard()

结论:静态代码仅执行一次,当首次生成这个类对象或者首次访问这个类的静态数据时(即第一次在代码中使用这个类)。先执行静态代码,再执行类的其他代码。

二、访问权限

1.权限大小顺序:public > protected > default > private

你可能感兴趣的:(Java,java学习)