Initializer block.

Ref:  Initializing Fields

  Instance initializers are permitted to refer to the current object via the keyword this,Ref:  Instance Initializers

 1 /*
 2 Initializer blocks,have the same capability as 'constructor',that is, they can use to initialze instance members.
 3 We use 'initialzer blocks',because all the instances of the class can have the same characteristic,such as 'cry'.
 4 */
 5 package kju.obj;
 6 
 7 import static kju.print.Printer.*;
 8 class InitializerBlock {
 9     public static void main(String[] args) {
10         Person p = new Person();
11         Person lily = new Person("Lily", 21);
12         printHr();
13         lily.cry();
14         /*prints begin:
15         name = null is crying
16         name = null is crying
17 
18         -----------------------------------
19         name = Lily is crying
20         :prints ends*/
21     }
22 }
23 
24 class Person {
25     {
26         cry();
27     }
28 
29     public Person() {
30         
31     }
32 
33     public Person(String name) {
34         this.name = name;
35     }
36 
37     public Person(String name, int age) {
38         this(name);
39         this.age = age;
40     }
41 
42     public void cry() {
43         println("name = " + name + " is crying");
44     }
45 
46     private String name;
47     private int age;
48 }

 

转载于:https://www.cnblogs.com/listened/p/3585297.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值