this关键字简单应用

 class PersonDemo3
{
public static void main(String[] args)
{
Person p=new Person("张三",22);
}
} /*
this 语句
1.用于构造函数间互相调用时使用,不能在一般函数中调用
2.this语句在构造函数中必须是第一句,并且在一个构造函数中只能使用一次
*/
//this关键字表示this所在函数所在的对象,用于标记对象的成员,避免出现歧义和出错,方便阅读
class Person
{
private int age;
private String name;
Person() //无参构造函数
{
System.out.println("A: name:"+this.name+","+"age:"+this.age); }
Person(String name) //一个参数构造函数
{
this.name=name;
//System.out.println("B: name:"+this.name+","+"age:"+this.age); }
Person(String name,int age) //两个参数构造函数
{
//this.name=name;
this(name);//使用this语句调用构造函数
this.age=age;
System.out.println("C: name:"+this.name+","+"age:"+this.age); }
}

输出结果:

C: name:张三,age:22

上一篇:C#算法基础之选择排序


下一篇:自动化运维工具之ansible(转)