super和this到底是什么

dreamhunter_lan dreamhunter_lan 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
回过头来再看的时候真的已经不知道它们分别是什么东西了,JLS上也就只是说它们是关键字。但是它们真正到底是什么呢?
对于super,《The Java Programming Language》上这样说:In field access and method invocation, super acts as a reference to the current object as an instance of its superclass.可以理解为在需要访问the hidden field和进行父类方法调用的时候,super表现为指向作为父类的一个实例的当前对象的一个引用。所以super只是act as a reference,但不是reference,对吗?我们也不可以将super赋给一个父类变量,比如在子类中:Super s = super;(报错)。当我们在构造方法中使用super()或其他形式的时候super又是什么呢?
对于this,JLS上这样表述:When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.这里:this也只是代表一个引用的值,还是没说this除了是keyword外还是什么,但是又说的this的类型。反正搞得一团乱,下面的代码输出的结果我也不理解:

class Super {
}

class SubClass extends Super{
public void foo() {
System.out.println(this.getClass());
System.out.println(super.getClass());
}
}

希望大家帮忙解惑,说说它们是什么。怎么使用它们就不用说了,所有的书上都差不多教我们怎么用了。谢谢~
...全文
评论 69
收藏 已收藏
分享
返回顶部
dreamhunter_lan
Java SE 62,620 成员 307,251 内容