这和超级java [英] this and super in java

查看:71
本文介绍了这和超级java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

超级关键字不是它们;那么我如何使用它们以与方法相同的方式将参数传递给构造函数?
简而言之,两者都能表现出如此明显的行为?

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 是关键字。 Java语言规范明确定义了它们的行为方式。简短的回答是这些关键字的行为特别,因为规范说它们必须。

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.


关键字this只能在实例方法,实例初始化程序或构造函数的主体中使用,或者在类的实例变量的初始化程序。如果它出现在其他任何地方,则会发生编译时错误。

The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

所以你可以使用这个作为函数的参数,以传递对当前对象的引用。但请注意,您不能使用 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 虽然因为这是在 15.11 中定义的有效:

You can use super.foo though because this is defined in 15.11 to be valid:

FieldAccess:
    Primary . Identifier
    super . Identifier
    ClassName .super . Identifier

规范还放限制超级如何使用


使用关键字super的特殊表单仅在实例方法,实例初始化程序或构造函数中有效,或在类的实例变量的初始值设定项中有效;这些与使用关键字的情况完全相同(§15.8.3)。

The special forms using the keyword super are valid only in an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class; these are exactly the same situations in which the keyword this may be used (§15.8.3).

这篇关于这和超级java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆