- this的作用
1.1 表示类中的属性
1.2 调用本类中的构造方法
其作用就是进行构造方法的重载
注意事项:
1.this 调用必须在构造方法体的首行
2.一个类中至少有一个不适用this 的构造函数
class Demo
{
private int age=25;
private String name="周海峰";
public Demo(){
System.out.println("输出无参的构造函数");
}
public Demo(int age){
this();//调用无参的构造函数
this.age=age;
}
public Demo(int age,String name){
this(age);//调用有一个参数的构造函数
this.name=name;
}
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
}
public class NewDemo
{
public static void main(String args[]){
Demo de1=new Demo();
System.out.println("姓名"+de1.getName()+",年龄"+de1.getAge());
Demo de2=new Demo(34);
System.out.println("姓名"+de2.getName()+",年龄"+de2.getAge());
Demo de3=new Demo(42,"邵阳");
System.out.println("姓名"+de3.getName()+",年龄"+de3.getAge());
}
}
运行的结果为:
1.3 表示当前对象 定义一个对象自己跟自己比较
class Demo
{
private int age=25;
private String name="周海峰";
public Demo(){
System.out.println("输出无参的构造函数");
}
public boolean Compare(Demo de){
Demo p1=de;
Demo p2=this;
if(p1==p2){
return true;
}
if(p1.name.equals(p2.name)&&p1.age==p2.age){
return true;
}else {
return false;
}
}
public Demo(int age){
this();//调用无参的构造函数
this.age=age;
}
public Demo(int age,String name){
this(age);//调用有一个参数的构造函数
this.name=name;
}
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
}
public class NewDemo
{
public static void main(String args[]){
Demo de1=new Demo(23,"周海峰");
Demo de2=new Demo(23,"安日成");
if(de1.Compare(de2))
{System.out.println("两个人相同");
}else{
System.out.println("两个人不相同");
}
}
}
运行的结果为: