我希望这不是一个愚蠢的问题.
有3个基本构造函数
public MyClass(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MyClass(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyClass(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
Run Code Online (Sandbox Code Playgroud)
每个都首先调用super类构造函数.那么它是否意味着我必须在这样的私有方法中放入所有常见的构造函数代码?:
public MyClass(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
common(context);
}
public MyClass(Context context, AttributeSet attrs) {
super(context, attrs);
common(context);
}
public MyClass(Context context) {
super(context);
common(context);
}
private void common(Context context) { ... }
Run Code Online (Sandbox Code Playgroud)
我虽然我可以链接构造函数的公共代码,但我得到一个错误,说构造函数调用必须是代码中的第一个语句.
public MyClass(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this(context, attrs);
}
public MyClass(Context context, AttributeSet attrs) {
super(context, attrs);
// Some code
this(context);
}
public MyClass(Context context) {
super(context);
// Some more code
}
Run Code Online (Sandbox Code Playgroud)
并且第一个语句要么是超级构造函数调用,要么是类构造函数调用,不能两者兼而有之.
Constructor call must be the first statement in a constructor
Run Code Online (Sandbox Code Playgroud)
最好的方法是使用this() - 您不需要创建新方法,并且您尊重DRY原则(不要重复自己)
public MyClass(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// your code here
}
public MyClass(Context context, AttributeSet attrs) {
// Assuming 0 is the default value of defStyle, else pass the default value
this(context, attrs, 0);
}
public MyClass(Context context) {
// Assuming null is the default value for attrs
this(context, null);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |