java面向对象(this关键字在构造函数间调用)-java读书笔记
时间:2014-04-23 23:46 来源: 我爱IT技术网 作者:山风
java面向对象(this关键字在构造函数间调用)
什么时候使用this?
用法1:5-10已讲
用法2:5-11已讲
用法3:构造函数之间调用,使用this语句。
1)一般函数的调用是 函数名称(参数列表);而构造函数之间的调用必须是 this(参数列表)
2)一般函数不可以调用构造函数,this语句只能用于构造函数中或之间。
3)规则:对 this 的调用必须是构造函数中的第一个语句。因为初始化要先执行,如果初始化中还有其它的初始化,则优先执行其它的。
4)构造函数间不可相互调用,否则造成死循环。
class Person
{
private String name;
private int age;
Person()
{
//this("haha"); //见4)
}
Person(String name)
{
this();
this.name=name;
}
Person(String name,int age)
{
this(name);
this.age=age;
}
}
class Test
{
public static void main(String[] args)
{
Person p1 = new Person("李四",30);
Person p2 = new Person("张三",36);
}
}
本文来源 我爱IT技术网 http://www.52ij.com/jishu/5594.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
