Thinking in java之构造器

首先,我们来看看this关键字这个神奇的关键字:

1.我们都知道利用this关键字在构造方法中对成员进行初始化:

private String Name;
	private int Age;
	private String Sex;
	
	public first_one(String Name,int Age,String Sex) {
		this.Age=Age;
		this.Name=Name;
		this.Sex=Sex;
	}
这是一种很常见的初始化方法。

下面介绍另一种this关键字的应用:

2.在构造器中调用构造器

  可能为一个类写了多个构造器,有时可能想在一个构造器中调用另一个构造器,以避免重复代码。则可用this做到这一点。

  贴出《Thingking in java》源代码(由于BZ未实现该书中的Print方法,故用..println方法来代替,实现打印):

//:initialization/Flower.java
//Calling constructor with "this"
import static net.mindview.util.Print.*;

public class Flower{
	int petalCount=0;
	String s="initial value";
	Flower(int petals){
		petalCount=petals;
		print("Constructor w/ int arg only,petalCount="+petalCount);
	}
	Flower(String ss){
		print("Constructor w/ String arg only,s= "+ss);
		s=ss;
	}
	Flower(String s,int petals){
		this(petals);
		//! this(s);//Can't call two!
		this.s=s;
		print("String & int args");
	}
	Flower(){
		this("hi",47);
		print("default constructor (no args)");
	}
	void printPetalCount() {
		//! this(11);//Not inside non-constructor!
		print("petalCount= "+petalCount+" s= "+s);
	}
	public static void main(String[] args) {
		Flower x=new Flower();
		x.printPetalCount();
	}

运行结果:

/*
    Constructor w/ int arg only,petalCount=47
    String & int args
    default constructor (no args)
    petalCount= 47 s= hi

*/
其次,我们介绍构造器的初始化:

构造器的初始化顺序:

      在类的内部,变量定义的先后顺序决定了初始化的顺序,贴出代码:

//initialization/OrderOfInitialization.java
//Demonstrates initialization order
import static net.mindview.util.Print.*;

//When the constructor is called to create a Window object,you'll see a message:
class Window{
	Window(int marker){
		print("Window("+marker+")");
	}
class House{
	Window w1=new Window(1);//Before constructor
	House(){
		//Show that we're in the constructor:
		print("House()");
		w3=new Window(33);//Reinitialize w3
	}
	Window w2=new Window(2);//After constructor
	void f() {
	    print("f()");
	}
	Window w3=new Window(3);//At end
}
public class OrderOfInitialization{
	public static void main(String[] args) {
		House h=new House();
		h.f();//Show that constructor is done
	}
}
执行结果:

/*
   Window(1)
   Window(2)
   Window(3)
   House()
   Window(33)
   f()


*/
注:我在编译的时候,当main方法中的static不去掉时就会报错,但是不知道什么原因,要是哪位友友知道希望能告诉我为啥,谢谢~









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值