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

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 Human
11 {
12     // constructor
13     // 然后再进行构造初始化
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 Human
12 {
13     // constructor 1
14     Human(int h)
15     {
16         System.out.println("construct 1 " + h);
17     }
18     
19     // constructor 2
20     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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值