java--面向对象this

package test;
/*this 关键字
 * this智能在对象方法内使用
 
 * */
class Person{
    String name;
    int age;
    /*对象方法
     * */
    
    public void setName(String name) {
        this.name = name;
    }
    public void playGame() {
        System.out.println(this.name+"在玩游戏");//this就是调用这个方法的那个对象的引用
        //本类的对象方法可以直接调用对象方法,隐藏了this,this就是调用playGame的p
        sleep();
    }
    public void sleep() {
        System.out.println(this.name+"睡觉");
    }
}

public class Demo1 {
    
    public static void main(String[] args) {
        //创建一个人对象
        Person p = new Person();
        p.name="肖战";
        System.out.println(p);
        //通过对象来调用对象方法
        p.playGame();
        
        Person p1 = new Person();
        p1.name="小赞";
        System.out.println(p1);
        p1.playGame();
    }
}
 

你可能感兴趣的:(java--面向对象this)