java 构造函数 this指针问题
2018-03-09 09:31
459 查看
若为类写了多个构建器,那么经常都需要在一个构建器里调用另一个构建器,以避免写重复的代码,可用 this
关键字做到这一点。 在构建器中,若为其赋予一个自变量列表,那么表,那么 this 关键字会具有不同的含
义:它会对与那个自变量列表相符的构建器进行明确的调用(局限在this调用次数、this位置)
Example:
public class simple_tree {
int height;
String name;
static int wi = 0;
simple_tree()
{
print("default simple_tree === ");
height = 0;
wi = 0;
}
simple_tree(int h)
{
print(" simple_tree " + h);
height = h;
++wi;
}
simple_tree(String na)
{
print(" simple_tree " + na);
name = na;
++wi;
}
simple_tree(String na, int h)
{
//print(" simple_tree " + na + " h " + h); //err
this(h);
//this(na); //only once
this.height = h;
print(" simple_tree " + na + " h " + h);
}
void info()
{
print("tree is = " + height + " wi = " + wi);
}
private static void print(String ss)
{
System.out.println(ss);
}
}
关键字做到这一点。 在构建器中,若为其赋予一个自变量列表,那么表,那么 this 关键字会具有不同的含
义:它会对与那个自变量列表相符的构建器进行明确的调用(局限在this调用次数、this位置)
Example:
public class simple_tree {
int height;
String name;
static int wi = 0;
simple_tree()
{
print("default simple_tree === ");
height = 0;
wi = 0;
}
simple_tree(int h)
{
print(" simple_tree " + h);
height = h;
++wi;
}
simple_tree(String na)
{
print(" simple_tree " + na);
name = na;
++wi;
}
simple_tree(String na, int h)
{
//print(" simple_tree " + na + " h " + h); //err
this(h);
//this(na); //only once
this.height = h;
print(" simple_tree " + na + " h " + h);
}
void info()
{
print("tree is = " + height + " wi = " + wi);
}
private static void print(String ss)
{
System.out.println(ss);
}
}
相关文章推荐
- 在DOc的构造函数中得到VIew类指针引起的问题(GetActiveView()引起的Access Violation;this->GetFirstViewPosition()=NULL;ASSERT(AfxIsValidAddress(this, siz
- java this调用函数及构造函数问题
- 构造函数中的this指针
- JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();出现空指针异常的问题
- Java语言深入-构造函数的继承问题
- MFC 孙鑫老师第二讲中有关this指针的问题
- 关于IE中的attachEvent函数的this指针问题(转)
- JAVA学习,this(),super()调用构造函数研究
- java.lang.IllegalStateException: getOutputStream() has already been called for this response问题
- Java中构造函数执行顺序的问题
- 赋值构造函数的用法即指针悬挂问题的产生和解决(中)——解决之道
- java 指针的问题
- 空指针问题(java.lang.NullPointerException)
- java.lang.NullPointerException空的指针问题
- java中指针的问题
- a标签伪协议触发事件和onclick触发事件的this指针问题
- Java中关于构造函数继承的相关问题
- a标签伪协议触发事件和onclick触发事件的this指针问题
- [转]C++中this指针理解汇总以及问题和解答
- Java语言深入-构造函数的继承问题 (转)