Java this关键字使用规则
2017-10-23 21:47
381 查看
this 关键字用来表示当前对象本身,或当前类的一个实例,通过 this 可以调用本对象的所有方法和属性。
1.使用在类中,可以用来修饰属性、方法、构造器。
2.表示当前对象,或者是当前正在创建的对象。
3.当形参和变量名重名时,如果方法内部需要使用成员变量,则需要在成员变量前面添加this关键词
4.在方法内中使用当前对象的成员变量或者成员方法,添加this关键词可以增强可阅读性
5.在构造其中可以使用 “this(形参列表)” 形式调用当前对象重载的构造器,且要存在首行
例如:
x + y = 25
上面的程序中,obj 是 Demo 类的一个实例,this 与 obj 等价,执行 int z = this.x + this.y;,就相当于执行 int z = obj.x + obj.y;。
注意:this 只有在类实例化后才有意义。
使用this区分同名变量
成员变量与方法内部的变量重名时,希望在方法内部调用成员变量,怎么办呢?这时候只能使用this,
例如:
网站的名字是微学苑,已经成立了3年
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年
相关文章推荐
- Java关键字final、static、this、super使用总结
- Java关键字this、super使用总结
- Java基础知识之this关键字的使用
- java中this和super关键字使用详解
- Java 关键字 this super 使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字final、static、this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java 关键字super和this的使用及区别
- Java关键字this,super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- java笔记 chapter3使用java类,关键字new,this,变量初始化,引用传递