this关键字
-----------siwuxie095
this 关键字:
(1)表示类中的属性和调用方法
(2)表示本类中的构造方法
(3)表示当前对象
代码1:
package com.siwuxie095.thisdemo; 
 class People{ private String name; private int age; 
 public People(String name,int age) { //代表构造方法,且必须放在首行,否则无法通过编译 this(); this.name=name; this.age=age; } 
 public People() { System.out.println("无参构造方法"); } 
 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } 
 public void tell() { System.out.println("姓名:"+this.getName()+" 年龄:"+this.getAge()); } 
 } 
 public class ThisDemo01 { 
 public static void main(String[] args) { People p=new People("张三",30); p.tell(); } 
 }  | 
运行一览:
		
代码2:
package com.siwuxie095.thisdemo; 
 class PeopleX{ 
 public void tell() { //this 表示当前对象 System.out.println(this); } } 
 public class ThisDemo02 { 
 public static void main(String[] args) { PeopleX p=new PeopleX(); //输出一致,可以通过这种方式比较两个对象是不是同一对象 System.out.println(p); p.tell(); } 
 }  | 
运行一览:
		
【made by siwuxie095】
posted on 2017-03-16 22:26 siwuxie095 阅读(110) 评论(0) 收藏 举报

                
            
        
浙公网安备 33010602011771号