Java技术文章技术文代码改变世界

构造代码块

2015-06-14  本文已影响1625人  许宏川

假设有个用户类User有这么多属性

public String userName; //用户名
public int age; //年龄
public String phone; //手机号
public String email; //邮箱

public int vip; //vip等级
public boolean isManager; //是否管理员

还有三个构造方法

//构造方法重载
public User(String userName, int age, String phone, String email) {
this.userName = userName;
this.age = age;
this.phone = phone;
this.email = email;
}

public User(String userName, int age, String phone, String email, int vip) {
this.userName = userName;
this.age = age;
this.phone = phone;
this.email = email;

this.vip = vip;
}

public User(String userName, int age, String phone, String email, boolean isManager) {
this.userName = userName;
this.age = age;
this.phone = phone;
this.email = email;

this.isManager = isManager;
}

你是不是发现,三个构造方法里有大量重复的初始化代码。聪明的你可能一下子就想到了可以把重复的代码提取出来,新建了一个init()把重复代码都丢进去。然后每个构造方法都调用init()。
例如像这样:

//构造方法重载
public User(String userName, int age, String phone, String email) {
init(userName, age, phone, email);
}

public User(String userName, int age, String phone, String email, int vip) {
init(userName, age, phone, email);

this.vip = vip;
}

public User(String userName, int age, String phone, String email, boolean isManager) {
init(userName, age, phone, email);

this.isManager = isManager;
}

//初始化
void init(String userName, int age, String phone, String email) {
this.userName = userName;
this.age = age;
this.phone = phone;
this.email = email;
}

哇,这么一来代码一下子简洁了很多。只不过你还不知道可以使用构造代码块让代码更简洁。我先告诉你代码怎么改:

public class User {

public String userName; //用户名
public int age; //年龄
public String phone; //手机号
public String email; //邮箱

public int vip; //vip等级
public boolean isManager; //是否管理员

//构造代码块,会在构造方法之前执行
{
System.out.println("构造代码块");
init(userName, age, phone, email);
}

//构造方法重载
public User(String userName, int age, String phone, String email) {
System.out.println("构造方法1");
}

public User(String userName, int age, String phone, String email, int vip) {
System.out.println("构造方法2");
this.vip = vip;
}

public User(String userName, int age, String phone, String email, boolean isManager) {
System.out.println("构造方法3");
this.isManager = isManager;
}

//初始化
void init(String userName, int age, String phone, String email) {
this.userName = userName;
this.age = age;
this.phone = phone;
this.email = email;
}

}

为了看到方法的执行顺序,我加了几个输出语句,接着测试一下吧:

User user1 = new User("张三", 20, "13800138000", "zhangsan@gmail.com");
User user2 = new User("李四", 20, "13800138000", "lisi@gmail.com", 2);
User user3 = new User("王五", 24, "13800138000", "wangwu@gmail.com", true);

运行结果:
<pre>
构造代码块
构造方法1
构造代码块
构造方法2
构造代码块
构造方法3
</pre>

从示例你应该你猜出构造方法块是干嘛的了。它在每次new一个新对象时都会被执行,而且是在构造方法之前。所以可以把每个构造方法的重复部分写在构造方法块里。语法就是一对{ }。

本文代码下载:百度网盘

上一篇下一篇

猜你喜欢

热点阅读