Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

this and super in 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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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();
    }
}

Result:

Program.java:5: '.' expected
    void run() { test(super); }

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

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

The specification also puts restrictions on how super can be used:

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...