我是这样想的
+----------------+
| 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 Language Specification:
super.Identifier 的形式是指名为Identifier 的字段
当前对象,但将当前对象视为
当前类的超类。
T.super.Identifier 的形式是指名为Identifier 的字段
对应于T 的词法封闭实例,但具有
instance 被视为T 的超类的一个实例。
用外行的话来说,this 基本上是一个对象(*the** 对象;您可以在变量中移动的同一个对象),实例化类的实例,数据域中的普通变量; super 就像是一个指向要执行的借用代码块的指针,更像是一个单纯的函数调用,它与调用它的类有关。
因此,如果你从超类中使用super,你会从superduper类[祖父母]执行代码),而如果你从超类中使用this(或者如果它被隐式使用)它会一直指向子类(因为没有人改变它 - 也没有人可以)。