现在的位置: 首页 > 综合 > 正文

一个程序说明java中this关键字

2013年08月12日 ⁄ 综合 ⁄ 共 601字 ⁄ 字号 评论关闭
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package arthur.com.shipin;

/**
 *测试this
 * @author Arthur
 */
public class ThisTest {
    //对象的名字
    private String name;
    ThisTest(){
        
    }
    
    ThisTest(String name){
        this.name = name;
    }
    /**
     * 打印当前对象(的名字)
     */
    public void printThis(){
        System.out.println(this);
    }
    
      /**
     * 重写toString 返回对象名
     * @return name
     */
    @Override
    public String toString(){
        return name;
    }
    
    public static void main(String args[]){
        //此时当前对象this指的是tt1
        ThisTest tt1 = new ThisTest("tt1");
        System.out.println(tt1);      
        tt1.printThis();
        
        System.out.println();
        
         //此时当前对象this指的是tt2
        ThisTest tt2 = new ThisTest("tt2");
        System.out.println(tt2);
        tt2.printThis();
    }
    

}

抱歉!评论已关闭.