Java中this的问题

今天学习Servlet中牵扯到了this这个关键字,下面做个笔记,也给大家一起参考学习一下。 
首先this是指当前运行类实例对象。当你创建一个对象并调用该对象的方法的时候其实下面这样的:
Person p = new Person();
  p.show(String name);

其实在编译之后编程机器语言是p.show(p , name);第一个参数是本类的对象的引用。而在这个show方法中怎么来用这个引用呢?其实就是用this来代替这个引用。也就是当前运行类实例对象。

而静态方法就是没有this的方法,也就是静态的方法中不能使用this,因为静态方法编译成机器语言之后,并没有在参数中加入本类对象的引用,也就是 p.show(String name)和原来一样。这就是this的由来。

下面说一下this的一些使用

public class Father {
    public void fun(){
        System.out.println("this is Father's fun");
        this.show();
    }
    public void show(){
        System.out.println("father's show : ");
    }
}

public class Son extends Father {
    public void fun(){
        System.out.println("this is Son's fun()");
        super.fun();
    }
    public void show(){
        System.out.println("Son's show() ");
    }
    public static void main(String[] args) {
        Son son = new Son();
        son.fun();
    }
}

在看到结果之前大家可以先猜一下是不是和自己想象的结果一样,结果如下:

this is Son's fun()
this is Father's fun
Son's show() 

有些人对this理解不深的可能会产生疑问,为什么结果会是这样。我在前面已经说过:”this是指当前运行类实例对象”,所以,要看是谁调用了这个方法。这里写图片描述
在父类中又通过this调用了show()方法,因为show方法是子类继承自父类的。而且,此时的this是指当前的调用者,图中已经说过,当前的调用者是son,所以此时的this也是son所以调用的show方法也就是子类的show方法了。

那么下面再给大家看一段代码:

public class Father {
    public String name ="father";
    public void fun(){
        System.out.println("this is Father's fun :"+this.name);
    }
}

public class Son extends Father {
   public String name="son";

    public void fun(){
        System.out.println("this is Son's fun() :" + this.name);
        super.fun();
    }
    public static void main(String[] args) {
        Son son = new Son();
        son.fun();
    }
}

仍然希望大家先猜一下结果。
结果如下:

this is Son's fun() :son
this is Father's fun :father

是不是觉得很诡异。
这里我解释一下。前面的例子中show方法时子类继承并覆盖了父类的方法,所以调用的是子类的show方法,如果子类没有重写父类的方法的话,其实仍旧调用父类的方法的(大家可以在父类中添加一个方法,用this调用一下试试。此处不在举例),但是字段不能覆盖,谁的就是谁的,子类继承了父类,字段在子类中就变成了 编译时类型的字段了(可以看一下我的上一篇博客又介绍),所以此时的this是调用自己的属性了,举个例子:

  public static void main(String[] args) {
        Son son = new Son();
        System.out.println(son.name);
        Father f = new Son();
        System.out.println(f.name);
    }

这里的运行结果就是:

son
father

这就牵扯到了多态。多态的特点是,成员变量编译时看左边,成员方法编译看左边,运行看右边

大家要记住方法是谁运行看谁,字段是谁的就是谁的。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值