JAVA中this的作用!

一、什么是this

先看一个简单示例:

public class Main{
    public static void main(String[] args){
         Person p1 = new Person("shimisi",80);

    }
}
//构造器
class Person{
    String name;
    int age;
    public Person(String name,int age)
    {
        this.name = name;
        this.age = age;
        System.out.println(name +"\t"+ age);
    }
}

二、this的注意事项和使用细节

1.哪个对象调用,this就代表哪个对象

this关键字:

1.this关键字可以用来访问本类的属性、方法、构造器

2.this用于区分当前类的属性和局部变量

3.访问成员方法的语法:this.方法名(参数列表);

4.访问构造器语法:this(参数列表); 注意只能在构造器中使用

5.this不能在类定义的外部使用,只能在类定义的方法中使用。

2.this快速入门:this访问构造器
//构造器快速入门
public class Main{
    public static void main(String[] args){
          T t1 = new T();
    }
}
//构造器
class T{

    public T()
    {
        //访问T(String name,int age)
        //如果有this访问构造器,必须放在第一条语句
        this("jake",18);
        System.out.println("T()构造器");
    }
    public T(String name,int age)
    {
        System.out.println("T(String name,int age)构造器");
    }
}
3.传统方法访问用就近原则
而this只关注于属性
public class Main{
    public static void main(String[] args){
          T t1 = new T();
          t1.m();
    }
}
//构造器
class T{
    String name = "jack";
    int age = 18;
    public void m()
    {
        String name = "smith";
        System.out.println("name " + name + " age " + age);//name = smith
        System.out.println("this.name " + this.name + " this.age " + this.age);
        //this.name = jack
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值