Java - super keyword in new Runnable thread - refers to non-stationary method via class

In all the tutorials for the super keywords that I found on the Internet, it’s hard to come close to the following examples. My question is:

  • What is the difference between Tracker.super.track(event); and test.parent.Tracker.track(event); ?

  • Why is the first job?

  • What does Tracker.super mean? An object or class?

Subclass

:

 package test; public class Tracker extends test.parent.Tracker { @Override public void track(final Event event) { Executor.execute(new Runnable() { public void run() { Tracker.super.track(event); //this works!! why?? super.track(event); // compile error: cannot resolve test.parent.Tracker.track(event); //compile error: can only reference static method } }); } } 

Super class

 package test.parent; public abstract class Tracker { public void track(Event event) {} } 

Help updates:

In jls8, 11.15.2

"Suppose that the access class expression T.super.f appears in class C, and the immediate superclass of the class, denoted by T, is a class whose full name is S. If f from S is accessible from C, then T.super.f is processed like this as if it were the expression this.f in the body of class S. Otherwise, a compile-time error occurs.

Thus, T.super.f can access the field f available in class S, even if this field is hidden by the declaration of the field f in class T.

This is a compile-time error if the current class is not an inner class of the class T or T.

+5
source share
1 answer

Your run() method is in an anonymous subclass of Runnable , where it is also an internal Tracker class.

Effectively the same as

 package test; public class Tracker extends test.parent.Tracker { ... @Override public void track(final Event event) { //anonymous class translated into local class class TrackerRunnable implements Runnable { public void run(){ Tracker.super.track(event); //this works!! why?? super.track(event); // compile error: cannot resolve test.parent.Tracker.track(event); //compile error: can only reference static method } } Executor.execute(new TrackerRunnable()); } } 

In Java, the inner class also has a reference to the outer class to which it "belongs". You should reference this on TrackerRunnable as this inside the launch, but if you need to access the Tracker instance with which the associated TrackerRunnable will have access to it as Tracker.this . Same thing with Tracker.super . Just super means the superclass TrackerRunnable not Tracker (in this case Runnable ).

The main thing to note is that this is the syntax that is used to resolve scope only in inner classes, and that Tracker here refers to "an instance of the Tracker class to which I belong." In the case of test.parent.Tracker.track Tracker refers to the β€œ Tracker class”, so you cannot call instance instances in the class itself.

+3
source

All Articles