49 面向对象this关键字的概述和应用

this 代表当前对象的引用 

用来区别成员变量和局部变量的重名

如果没有加this 在成员变量和局部变量重名的情况下 ,就近原则 ,此时的赋值代表赋值给方法的局部变量,没有赋值给对象的属性.

 

 1 class Demo6_phone{
 2     public static void main(String[] args) {
 3         Phone p1 = new Phone();
 4         p1.setPrice(2000);
 5         p1.setBrand("XIAOMI");
 6         System.out.println(p1.getBrand());
 7         System.out.println(p1.getPrice());
 8         p1.call();
 9         p1.sendMessage();
10         p1.playGame();
11     }
12 }
13 
14 class Phone{
15     private String brand;
16     private int price;
17 
18 
19     public void setBrand(String brand){
20         this.brand = brand;
21 
22     }
23 
24     public String getBrand(){
25         return this.brand;
26     }
27 
28     public void setPrice(int price){
29         this.price = price;
30 
31     }
32 
33     public int getPrice(){
34         return this.price;
35     }
36 
37     public void call(){
38         System.out.println("call()");
39     }
40 
41     public void sendMessage(){
42         System.out.println("sendMessage()");
43 
44     }
45 
46     public void playGame(){
47         System.out.println("call()");
48 
49     }
50 }

 

posted @ 2017-01-24 23:19  panw3i  阅读(148)  评论(0编辑  收藏  举报