java 中 this 和 super 关键字的区别(更多高级信息)
The difference between this and super keywords in java (More advanced information)
我了解到此关键字用于在特定 class 中调用当前构造函数。但是我有另一种情况,我需要更多地了解它。下一个代码显示了 this 和 super 关键字的使用:
public class Stack {
public void push()
{
/* do something */
}
public boolean full()
{
/* do something */
}
}
另一个class是:
public class ProtectedStack extends Stack {
public void push()
{
if (this.full()){----}
else
{
super.push();
}
}
}
我想知道在这种情况下会发生什么。
它非常明确 this
调用当前对象的方法并且 super
调用当前对象的父对象的方法(注意在调用过程中该方法是以递归方式搜索直到找到。).
来自评论,在您的情况下,您没有在子类 this.full()
和 full()
和 [= 上实现 full()
方法15=] 相同。
另外,this.full()
和 full()
总是相同的,不要使用 this.full()
模式来减少混淆。
this.full()
与full()
完全相同。它在 ProtectedStack
实例上调用方法 full()
。此方法 可能 直接在 ProtectedStack
class 中声明,也可能被继承。在您的代码中,方法 full()
似乎是从父 class Stack
继承的,因为 ProtectedStack
没有覆盖它。
关于super.push()
,这将总是调用在最近的父class中实现的方法push()
。即使在 ProtectedStack
中重写此方法,也会调用父方法。
基本上:
this.method()
:在这个对象上调用了方法method()
,所以在这个class中查找方法,然后在父class中查找方法,以此类推。如果这个 class 覆盖它,然后这个将被调用。如果没有,将调用来自父级的,等等。
super.method()
:父class的方法method()
总是被调用,即使这个class覆盖了它。
我了解到此关键字用于在特定 class 中调用当前构造函数。但是我有另一种情况,我需要更多地了解它。下一个代码显示了 this 和 super 关键字的使用:
public class Stack {
public void push()
{
/* do something */
}
public boolean full()
{
/* do something */
}
}
另一个class是:
public class ProtectedStack extends Stack {
public void push()
{
if (this.full()){----}
else
{
super.push();
}
}
}
我想知道在这种情况下会发生什么。
它非常明确 this
调用当前对象的方法并且 super
调用当前对象的父对象的方法(注意在调用过程中该方法是以递归方式搜索直到找到。).
来自评论,在您的情况下,您没有在子类 this.full()
和 full()
和 [= 上实现 full()
方法15=] 相同。
另外,this.full()
和 full()
总是相同的,不要使用 this.full()
模式来减少混淆。
this.full()
与full()
完全相同。它在 ProtectedStack
实例上调用方法 full()
。此方法 可能 直接在 ProtectedStack
class 中声明,也可能被继承。在您的代码中,方法 full()
似乎是从父 class Stack
继承的,因为 ProtectedStack
没有覆盖它。
关于super.push()
,这将总是调用在最近的父class中实现的方法push()
。即使在 ProtectedStack
中重写此方法,也会调用父方法。
基本上:
this.method()
:在这个对象上调用了方法method()
,所以在这个class中查找方法,然后在父class中查找方法,以此类推。如果这个 class 覆盖它,然后这个将被调用。如果没有,将调用来自父级的,等等。super.method()
:父class的方法method()
总是被调用,即使这个class覆盖了它。