【Java 基础篇】【第五课】类的构造函数

来源:互联网 发布:淘宝抱歉无法付款方式 编辑:程序博客网 时间:2024/05/29 14:14
Java 也有自己的构造函数,如同c++一样有两个特征:

1.构造函数的名字和类的名字相同

2.构造函数没有返回值

 

下面来看一下这个例子:

 1 public class test  2 { 3     public static void main(String[] args)  4     { 5         Human aman = new Human(20); 6     } 7 } 8  9 10 class Human11 {12     // constructor13     // 然后再进行构造初始化14     Human(int h)15     {16         System.out.println("construct  height is " + height);17         this.height = h;18         System.out.println("construct  height is " + height);19     }20     21     // 首先初始化这里22     private int height = 10;23 }

输出 是这样的:

construct  height is 10
construct  height is 20

根据上面的代码,可以得出:

构建方法 > 显式初始值 > 默认初始值

 

重载:

当然一个类可以有多个构造函数,就像C++一样

 1 public class test  2 { 3     public static void main(String[] args)  4     { 5         Human aman = new Human(20); 6         Human bman = new Human(60, "hello"); 7     } 8 } 9 10 11 class Human12 {13     // constructor 114     Human(int h)15     {16         System.out.println("construct 1 " + h);17     }18     19     // constructor 220     Human(int h, String str)21     {22         System.out.println("construct 2 " + h + " " + str );23     }24 }

输出结果:
construct 1 20
construct 2 60 hello

 

当然不止构造函数可以重载,只要是类的函数就都可以重载

 

应该很好理解吧 ~~

0 0