this.关键字的小应用

//this可以使用在实例方法中,不能使用在静态方法中
public
class test { public static void main(String[] args) { Customer n1 = new Customer("小明"); n1.shopping(); Customer n2 = new Customer("小红"); n2.shopping(); } } //定义一个顾客类 class Customer{ //顾客的属性(实例变量) String name; //无参 public Customer(){ } //有参 public Customer (String s){ name = s; } //顾客的方法(实例方法) public void shopping(){ //System.out.println(name+"正在购物中"); //this.是可以省略的 //this. 省略的话,还是默认访问“当前对象”的name。 System.out.println(this.name+"正在购物中"); } }

 

posted on 2022-10-25 10:48  三岁学JAVA  阅读(21)  评论(0)    收藏  举报