我是这样想的
+----------------+
| 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
是指与Identifier
相对应的词汇包围实例的名称字段T
,但将该实例视为的超类的实例T
。
用外行的术语来说,this
基本上是一个对象(* the **对象;可以在变量中移动的同一对象),实例化类的实例,数据域中的普通变量;super
就像是指向要执行的借用代码块的指针,更像是单纯的函数调用,它相对于被调用的类。
因此,如果您super
从超类使用,您将从超级duper类[祖父母]执行代码,而如果您this
从超类使用(或隐式使用)代码,则它会一直指向子类(因为没有人更改它,并且没人可以)。