问题描述
此
和超级
关键字不是它们;那么我如何使用它们以与方法相同的方式将参数传递给构造函数?
简而言之,两者都能表现出如此明显的行为?
this
and super
are keywords aren't they; then how can I use them for passing arguments to constructors the same way as with a method??In short how is it that both can show such distinct behaviors??
推荐答案
你是正确的两个此
和 super
是关键字。 明确定义了它们的行为方式。简短的回答是这些关键字的行为特别,因为规范说它们必须。
You are correct that both this
and super
are keywords. The Java language specification defines explicitly how they must behave. The short answer is that these keywords behave specially because the specification says that they must.
根据规范这个
可以使用 (仅限某些地方)或。
According to the specification this
can be used a primary expression (only in certain places) or in an explicit constructor invocation.
所以你可以使用这个
作为函数的参数,以传递对当前对象的引用。但请注意,您不能使用 super
,就像它不是主表达式一样:
So you can use this
as an argument to a function to pass a reference to the current object. However note that you cannot use super
in the same way as it is not a primary expression:
public class Program
{
void test(Program p) {}
void run() { test(super); }
public static void main(String[] args)
{
new Program().run();
}
}
结果:
Program.java:5: '.' expected
void run() { test(super); }
你可以使用 super.foo
虽然因为这是在中定义的有效:
You can use super.foo
though because this is defined in 15.11 to be valid:
FieldAccess:
Primary . Identifier
super . Identifier
ClassName .super . Identifier
规范还放:
这篇关于这和超级java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!