首页 > 其他 > 详细

面向对象this关键字的内存图解

时间:2017-04-12 02:03:59      阅读:133      评论:0      收藏:0      [点我收藏+]

 

this:哪个对象调用方法,this就代表哪个对象

案例1:

//定义老师类
class Teacher {
    private String name;
    private int age;

    public String getName(){
        return name; 
        //return this.name;这里隐含了this,
        //因为局部没有name变量,所以不需要写this
    }

    public int getAge(){
        return age;
    }

    public void setName(String name){
        this.name = name;
    }

    public void setAge(int age){
        this.age = age;
    }

}

class Test{
    public static void main(String[] args){
        Teacher t = new Teacher();
        t.setName("张三");
        t.setAge(23);
        System.out.println(t.getName() + "---" + t.getAge());

        Teacher t2 = new Teacher();
        t2.setName("李四");
        t2.setAge(30);
        System.out.println(t2.getName() + "---" + t2.getAge());
    }
}

输出:

张三---23
李四---30

 

面向对象this关键字的内存图解

原文:http://www.cnblogs.com/happy520/p/6697027.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!