thinking in java的一些代码:http://www.mindviewinc.com/Books/TIJ4/java
构造函数的做用是在建立对象的时候初始化对象函数
package init;
/** * @author sawshaw *对象初始化 */ public class ObjectInit { private int a,b; public ObjectInit(){ //不带参数的默认构造器 System.out.println("调用了无参构造函数"); } public ObjectInit(int i){ //带参数的初始化 System.out.println("调用了有参构造函数"); } //对象初始化对属性赋值 public ObjectInit(int a,int b){ this.a=a; this.b=b; } public static void main(String[] args) { ObjectInit o=new ObjectInit(); o.getValue(); ObjectInit o1=new ObjectInit(6); o1.getValue(); ObjectInit o2=new ObjectInit(6,7); System.out.println(o2.a+","+o2.b); } public void getValue(){ System.out.println("===="); } }
缺省构造器 若是已经定义了一个构造器不管是否有参仍是无参,编译器不会自动为你再建立默认的无参构造器,因此若是this
package init;
/** * @author sawshaw *对象初始化 */ public class ObjectInit { private int a,b; /*public ObjectInit(){ //不带参数的默认构造器 System.out.println("调用了无参构造函数"); }*/ public ObjectInit(int i){ //带参数的初始化 System.out.println("调用了有参构造函数"); } //对象初始化对属性赋值 public ObjectInit(int a,int b){ this.a=a; this.b=b; } public static void main(String[] args) { ObjectInit o=new ObjectInit(); o.getValue(); ObjectInit o1=new ObjectInit(6); o1.getValue(); ObjectInit o2=new ObjectInit(6,7); System.out.println(o2.a+","+o2.b); } public void getValue(){ System.out.println("===="); } }
注释默认的构造器,那么ObjectInit o=new ObjectInit();
是会报错的,由于没有默认的无参构造器spa