Java的构造函数

一、Java构造函数的定义
   一个构造函数是对象被创建时初始对象的成员函数。它具有和它所在的类完全一样的名字。一旦定义好一个构造函数,创建对象时就会自动调用它。构造函数没 有返回类型,即使是void类型也没有。这是因为一个类的构造函数的返回值的类型就是这个类本身。构造函数的任务是初始化一个对象的内部状态,所以用 new操作符创建一个实例后,立刻就会得到一个清楚、可用的对象。

构造函数(方法)注意几个特点:

1.函数名与类名相同

2.没返回、没有方法类型、也不能定义成void

3.程序自动调用、一个类可以定义多个构造函数,构造函数可以重载、以参数的个数,类型,或排列顺序区分

二、构造函数继承解析

现有以下几个类:

 
 public class Grandfather {  
       
     public Grandfather(){  
         System.out.println("This is Grandfather!");  
     }  
       
     public Grandfather(String s){  
         System.out.println("This is Grandfather"+s);  
     }  
 }  
  
 public class Father extends Grandfather {  
  
     public Father(){  
         System.out.println("This is Father!");  
     }  
     public Father(String s){  
         System.out.println("This is Father!"+s);  
     }  
 }  
  
 public class Son extends Father {  
  
     public Son(){  
         System.out.println("This is Son!");  
     }  
     public Son(String s){  
         System.out.println("This is Son"+s);  
     }  
 }  
  
 public class Construct {  
  
     /**  
      * @param args  
      */ 
     public static void main(String[] args) {  
  
         Son son = new Son();  
         System.out.println("**********************************");  
         Son son1 = new Son("**==**");  
  
     }  
}
  

执行结果:

This is Grandfather!
This is Father!
This is Son!
**********************************
This is Grandfather!
This is Father!
This is Son**==**
从控制台打印的结果可以看出,当执行子类时,都是去找它的父类的缺省的构造函数,先执行父类的构造函数,再执行子类的本身。

针对以上情况,我们现在做个修改,改其中的一个类的代码如下:把Grandfather类显式写出的缺省构造函数注释掉

public class Grandfather {  
          
    //  public Grandfather(){  
    //      System.out.println("This is Grandfather!");  
    //  }  
    //      
        public Grandfather(String s){  
            System.out.println("This is Grandfather"+s);  
        }  
   } 

如果你用的是IDE开发工具,可以很快的就发现,继承这个Grandfather类的Father类,就已经报错了

我们就得出结论:
   如果不指定的情况下,子类有多个构造函数的时候,父类要嘛没有构造函数,要嘛最少有一个显式写出的缺省构造函数供子类构造函数调用.

如果要指定子类调用父类的某个构造函数,则要把代码改写如下:

public class Father extends Grandfather {  
  
     public Father(){  
         super("**ss**");  
         System.out.println("This is Father!");  
     }  
     public Father(String s){  
         super(s);  
         System.out.println("This is Father!"+s);  
     }  }

这样就指定了,作为子类的Father类,指定了调用父类Grandfather类的Grandfather(String s)构造函数

执行Construct.java

控制台输出为:

This is Grandfather**ss**
This is Father!
This is Son!
**********************************
This is Grandfather**ss**
This is Father!
This is Son**==**

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值