想拥有海绵宝宝的微笑

导航

java 构造方法详解

构造方法(构造器)
    是一种特殊的方法,该方法只有功能:构造对象
    特点:
        1.没有返回值
        2.构造方法的名称一定和类名一致
        3.不能在构造方法中写return
    java虚拟机会默认对每一个类提供空的构造方法,但是一旦自己提供了其他有参的构造方法,系统不会再提供无参构造方法
    当提供了其他构造方法,一般会在类中提供无参构造方法
    当你要创建对象时,先要看类的构造方法
    在java中,"初始化"和"分离"捆绑在一起,两者不能分离

     摘自<java编程思想>中的代码说明
    
    1.空构造方法   

 1 class Rock{
 2     Rock(){        //无参构造方法
 3         System.out.println("Rock ");
 4     }
 5 }
 6 public class SimpleConstructor(){
 7     public static void main(String[] args){
 8         for(int i=0;i<5;i++){
 9             new Rock();
10         }
11     }
12 }
13 /* 结果:Rock Rock Rock Rock Rock */

        无参构造方法的作用是创建一个"默认对象",如果自己的类中没有构造方法,则编译器会自动创建一个默认构造方法,如果已经定义,则不会再自动创建
    2.有参构造方法

 1 class Bird{
 2     //构建对象的时候,直接给属性赋值,通过有参的构造方法
 3     Bird(int i){}
 4     Bird(double i){}
 5 }
 6 public class SimpleConstructor(){
 7     public static void main(String[] args){
 8         //Bird bird1 = new Bird();    //没有默认构造方法
 9         Bird bird2 = new Bird(1);
10         Bird bird3 = new Bird(1.0);
11     }
12 }

        行8 bird1会报错,没有找到匹配的构造方法
    3.构造方法的初始化
        在类的内部,若变量全都是非static变量,则变量定义的先后顺序决定初始化的顺序,若有static变量,则先初始化static变量。(变量初始化顺序取决于有无static)
        即使变量定义散布于方法定义之间,它们仍旧会在任何方法(包括构造器)被调用之前得到初始化。

 1 class House{
 2     Window(int marker){System.out.println("Window( "+marker+")");}
 3 }
 4 class House{
 5     Window w1 = new Window(1);    //在构造器之前定义
 6     House(){
 7         System.out.println("House");
 8         w3 = new Window(33);    
 9     }
10     Window w2 = new Window(2);    //在构造器之后定义
11     public void f(){System.out.println("f()");}
12     Window w3 = new Window(3);    //最后定义
13 }
14 public class OrderOfInitialization{
15     public static void main(String[] args){
16         House h = new House();
17         h.f();
18     }
19 }
20 /* Window(1) Window(2) Window(3) House() Window(33) f() */   

        w3这个引用会被初始化两次:一次是在调用构造器前,一次是在调用期间(第一次引用的对象将被丢弃,并作为垃圾回收)
        
    4.构造方法中调用构造方法
        在文章"java this关键字"中详细说明

    5.出现继承关系时的构造方法
        子类中所有的构造方法都会默认访问父类空的构造方法
        一旦建立继承关系,子类就会在自己的构造方法中默认调用父类去参构造方法

 1 public class 继承05{    
 2     public static void main(String[] args){
 3         Zi zi = new Zi();
 4     }
 5 }
 6 class Fu{
 7     public int i;
 8     public Fu(){
 9         System.out.println("父类的构造方法...");    
10     }
11     public Fu(int i){
12         System.out.println("父类带参的构造方法...");    
13         this.i = i;
14     }
15 }
16 class Zi extends Fu{
17     public Zi(){
18         //super();   //隐式语句  不写编译器也会自动加上
19         //super(10);
20         System.out.println("子类的构造方法...");    
21     }
22 }
23 /*
24     父类的构造方法...
25     子类的构造方法...
26 */

    行18中编译器会自动调用super();,自己加上也没错,super() --> 调用父类空的构造方法
    行19 super(10) --> 调用父类带参的构造方法
       

posted on 2017-03-05 09:56  想拥有海绵宝宝的微笑  阅读(326)  评论(0编辑  收藏  举报