我这样想
+----------------+
| super |
+----------------+ <-----------------+
| +------------+ | |
| | this | | <-+ |
| +------------+ | | |
| | @method1() | | | |
| | @method2() | | | |
| +------------+ | | |
| method4() | | |
| method5() | | |
+----------------+ | |
We instantiate that class, not that one!
让我把这个子类稍微向左移一下,以便显示下面的内容...
(哇,我真的很喜欢ASCII图形)
We are here
|
/ +----------------+
| | super |
v +----------------+
+------------+ |
| this | |
+------------+ |
| @method1() | method1() |
| @method2() | method2() |
+------------+ method3() |
| method4() |
| method5() |
+----------------+
Then we call the method
over here...
| +----------------+
_____/ | super |
/ +----------------+
| +------------+ | bar() |
| | this | | foo() |
| +------------+ | method0() |
+-> | @method1() |--->| method1() | <------------------------------+
| @method2() | ^ | method2() | |
+------------+ | | method3() | |
| | method4() | |
| | method5() | |
| +----------------+ |
\______________________________________ |
\ |
| |
...which calls super, thus calling the super's method1() here, so that that
method (the overidden one) is executed instead[of the overriding one].
Keep in mind that, in the inheritance hierarchy, since the instantiated
class is the sub one, for methods called via super.something() everything
is the same except for one thing (two, actually): "this" means "the only
this we have" (a pointer to the class we have instantiated, the
subclass), even when java syntax allows us to omit "this" (most of the
time); "super", though, is polymorphism-aware and always refers to the
superclass of the class (instantiated or not) that we're actually
executing code from ("this" is about objects [and can't be used in a
static context], super is about classes).
换句话说,引用自
Java语言规范:
表单super.Identifier
指的是当前对象的名为Identifier
的字段,但将当前对象视为当前类的超类的实例。
表单T.super.Identifier
指的是名为T
的词汇封闭实例对应的名为Identifier
的字段,但将该实例视为T
的超类的实例。
通俗易懂地说,
this
基本上是一个对象(*那个**对象;你可以在变量中移动的同一个对象),实例化类的实例,数据域中的普通变量;
super
就像是一个指向要执行的借来的代码块的指针,更像是一个简单的函数调用,并且它是相对于调用它的类而言的。
因此,如果您从超类使用
super
,则会执行来自超级父类[祖父母]的代码,而如果您从超类使用
this
(或者如果它被隐式使用),它将继续指向子类(因为没有人更改它-也没有人能够)。