This is super in java

thisand superare keywords, it’s not they; then how can I use them to pass arguments to constructors in the same way as with a method? In short, how can one show that both can exhibit such behavior?

+6
source share
7 answers

You are correct that and thisand superare the key words. The Java language specification explicitly defines how they should behave. Short answer: these keywords behave on purpose, because the specification says that they should.

According to the specification this, a primary expression can be used (only in certain places) or in an explicit constructor call .

This keyword can only be used 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 elsewhere, a compile-time error occurs.

Thus, you can use thisas an argument functions to pass a reference to the current object. However, note that you cannot use the supersame as this is not the main 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 it super.foobecause it is defined in 15.11 to be valid:

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

super:

, super, , ; , this (§15.8.3).

+7

Java , .

(...) -, , super (...) -, .

Java , (.. ).

. , ++ .

+3

, , . , :

super("I'm a string!", 32);

, String int .

+1

, . , , :

public class MyException extends Exception {    
public MyException()
{

}

public MyException(String message)
{
    super(message);
}

public MyException(String string, Throwable e) 
{
    super(string, e);
} 
} 
+1

,

. . .

0

, . this , this(arg) constructor class. , super() , constructor super. constructor.

0
source

According to Wikipedia , thisand superare keywords, namely how they go away with all their magic, I suppose.

-1
source

All Articles