您的位置:首页 > 编程语言 > Java开发

Java this关键字使用规则

2017-10-23 21:47 381 查看
    this 关键字用来表示当前对象本身,或当前类的一个实例,通过 this 可以调用本对象的所有方法和属性。

         1.使用在类中,可以用来修饰属性、方法、构造器。

         2.表示当前对象,或者是当前正在创建的对象。

         3.当形参和变量名重名时,如果方法内部需要使用成员变量,则需要在成员变量前面添加this关键词

         4.在方法内中使用当前对象的成员变量或者成员方法,添加this关键词可以增强可阅读性

         5.在构造其中可以使用 “this(形参列表)” 形式调用当前对象重载的构造器,且要存在首行

例如:

public class Demo{
public int x = 10;
public int y = 15;
public void sum(){
// 通过 this 点取成员变量
int z = this.x + this.y;
System.out.println("x + y = " + z);
}

public static void main(String[] args) {
Demo obj = new Demo();
obj.sum();
}
}
运行结果:

x + y = 25

    上面的程序中,obj 是 Demo 类的一个实例,this 与 obj 等价,执行 int z = this.x + this.y;,就相当于执行 int z = obj.x + obj.y;。

注意:this 只有在类实例化后才有意义。

使用this区分同名变量

成员变量与方法内部的变量重名时,希望在方法内部调用成员变量,怎么办呢?这时候只能使用this,

例如:

public class Demo{
public String name;
public int age;

public Demo(String name, int age){
this.name = name;
this.age = age;
}

public void say(){
System.out.println("网站的名字是" + name + ",已经成立了" + age + "年");
}

public static void main(String[] args) {
Demo obj = new Demo("微学苑", 3);
obj.say();
}
}
运行结果是  :

网站的名字是微学苑,已经成立了3年
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: