首页 > 学院 > 开发设计 > 正文

(第五章)java面向对象之this的作用总结

2019-11-15 00:38:58
字体:
来源:转载
供稿:网友
(第五章)java面向对象之this的作用总结

this关键字总是指向调用该方法的对象。

this可以代表任何对象,当this出现在某个方法体中时,它所代表的对象是不确定的,但它的类型是确定的,它所代表的对象只能是当前类的(在那个类中就是那个类),只有当这

个方法被调用时,它所代表的对象才被确定下来。谁在调用这个方法,this就代表谁。

〉在构造器中引用该构造器正在初始化的数据

〉在方法中引用调用该方法的对象

this关键字最大的作用就是让类中的一个方法,访问该类中另一个方法或实例变量。

public class Dog{    public void jump(){        system.out.PRintln("正在执行jump()方法");    }    public void run(){        //this 引用调用run()方法中的对象        //this代表run()对象        this.jump();    }}

this在构造器中代表该构造器正在初始化的对象。

public class Test{    //定义一个foo成员变量    public int foo;    public ThisInContructor()    {        //在构造器中定义一个foo局部变量        int foo = 0;        //使用this代表该构造器正在初始化的对象        //下面的代码会将该构造器正在初始化的对象的foo成员变量设为6        this.foo = 6;    }     public static void main(String[] args)     {        //输出6        System.out.println(new ThisInContructor().foo)    }}

如果方法中有个局部变量和成员变量同名,而程序又需要访问这个被覆盖的成员变量,则必须使用this。

public class Test{    private String name = "李刚";    private static double price = 78.0;    public static void main(String[] args)     {        int price = 65;        //输出65,局部变量覆盖了成员变量        System.out.println(price);        //输出78.0        System.out.println(Test.price);        //运行info()方法        new Test.info();    }    public void info()    {        String name = "小明";        //输出小明        System.out.println(name);        //使用this来作为name变量的限定        //输出,李刚        System.out.println(this.name);    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表