this关键字----使用场景一

xiaoxiao2021-02-28  111

/* 当成员变量和局部变量重名,可以用关键字this来区分。 this:代表对象。代表哪个对象呢? 当前对象。 this就是所在函数所属对象的引用。 简单说:哪个对象调用了this所在的函数, 使用场景一:提高阅读性 如下列构造函数中参数n 很难知道是代码的意图是什么。可直接用name这时,两个name,需要用this关键字来区分。 */ class Student{ private String name; private int age; Student(String name)//构造函数 { this.name = name; } public void speak() { System.out.println(name+":"+age); } } public class Demo_6 { public static void main(String[] args) { // TODO Auto-generated method stub Student p = new Student("旺财"); p.speak(); } }
转载请注明原文地址: https://www.6miu.com/read-50537.html

最新回复(0)