`
yxwang0615
  • 浏览: 552825 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

thinking in java 4 笔记之构造器

    博客分类:
  • java
阅读更多
1.由于构造器的名称必须与类名完全相同,所以“每个方法首字母小写”的编码风格并不适用于构造器,因为类名首字母是大写的。
2.根据方法的返回值来区分重载方法是性不通的。
3.如果你写的类中没有构造器,则编译器compiler会自动帮你创建一个默认的构造器。如果已经定义了一个构造器(无论是否有参数),compiler就不会帮你自动创建默认构造器。
4.static关键字不能应用于局部变量,只能作用于域(域就是范围的意思
例{}之间,称为一块域,用来描述变量适用范围,全局变量的域是整个类,局部变量只适用于他所在的{}之间)。
5.构造器的初始化顺序:在类的内部,变量定义的先后顺序决定了初始化的顺序。即使变量定义散布于方法定义之间,他们仍然会在任何方法(包括构造器)被调用之前得到初始化。
eg:
//窗户类:
public class Window {
	//when the constructor is called to create 
	//a window object,you'll see a message:
	public Window(int marker) {
		System.out.println("Window(" + marker + ")");
	}	
}
//房子类:
public class House {
	Window w = new Window(1); //before constructor

	public House() {
         w1 = new Window(2); //reinitialize w1,假设构造器首先初始化,
                                 //那么这里会报w1未定义的错误
	}
    public void printf()
    {
    	System.out.println("system out something...");
    };
	Window w1 = new Window(3); //after constructor
	
}

    public  static void main(String[] args) {
           House h = new House();
           h.printf();
     }/**Output
       Window(1)
       Window(3) 
       Window(2)
       system out something... */     
}

6.静态变量和非静态变量的初始化顺序
public class Bowl {
	Bowl(int marker)
	{
		System.out.println("Bowl(" + marker + ")");
	}
	void f1(int marker)
	{
		System.out.println("f1(" + marker + ")");
	}
	//System.out.println();
}

public class Table {
	static Bowl bowl1 = new Bowl(1);

	public Table() {
		System.out.println("Table()");
		bowl2.f1(1);
	}
	void f2(int marker)
	{
		System.out.println("f2(" + marker + ")");
	}
	static Bowl bowl2 = new Bowl(2);	
}

public class Cupboard {
	Bowl bowl3 = new Bowl(3);
	static Bowl bowl4 = new Bowl(4);
	public Cupboard() {
		System.out.println("Cupboard()");
		bowl4.f1(2);
		
	}
	void f3(int marker)
	{
		System.out.println("f3(" + marker + ")");
	}
	static Bowl bowl5 = new Bowl(5);
	
}

public class StaticInitialization {
	public static void main(String[] args) {
		System.out.println("creating new Cupboard()in main");
		new Cupboard();
		System.out.println("creating new Cupboard()in main");
		new Cupboard();
		table.f2(1);
		cupboard.f3(1);
	}
	static Table table = new Table();
	static Cupboard cupboard = new Cupboard();
}
/*Output:
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
creating new Cupboard()in main
Bowl(3)
Cupboard()
f1(2)
creating new Cupboard()in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
*/


类初始化时按先static后非static变量初始化的顺序原则初始化各个变量,两次执行new Cupboard(),但第二次只打印了Bowl(3),是因为第一次中某些static变量已经静态初始化过了,静态初始化动作只能进行一次。

从上述打印中看出,类中成员的初始化顺序为(从早到晚):
静态变量 > 非静态变量 > 构造器 > 方法


详细的顺序如下:
(1) 先是父类的static变量和static初始化块

(2)然后是子类的static变量和static初始化块  

(3)父类的实例变量、初始化快

(4)父类的构造方法

(5)子类的实例变量、初始化快

(6)子类构造方法
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics