Thinking in java之构造器

来源:互联网 发布:车铣复合手工编程例子 编辑:程序博客网 时间:2024/06/05 17:06

首先,我们来看看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 orderimport 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 constructorHouse(){//Show that we're in the constructor:print("House()");w3=new Window(33);//Reinitialize w3}Window w2=new Window(2);//After constructorvoid 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不去掉时就会报错,但是不知道什么原因,要是哪位友友知道希望能告诉我为啥,谢谢~