Home > Software engineering >  Java "this" usage
Java "this" usage

Time:11-05

I am new to Java. I am reading a toy code, and notice all the other methods expect "start" and "stop" methods are static. And due to this "stop" can only be called as via ".this.stop()" (The "here" line). What's the advantage implement like this, why not make "start" and "stop" also static methods?

public class MyService {
    private MyService() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    MyService.this.stop();                    <----- here
                } catch (IOException | InterruptedException e) {
                    ...
                }
            }
        });
    }

    protected void stop() {
     ....
    }

    protected void start() {
     ....
    }

    public static xxx getXXX() {
        return xxx;
    }
    ....
}

CodePudding user response:

The problem is that the stop() call is inside an anonymous class extending Thread so it has its own stop() method inherited from Thread:

...
       new Thread() {
            @Override
            public void run() {
                try {
                    MyService.this.stop();                    <----- here
                } catch (IOException | InterruptedException e) {
                    ...
                }
            }
        }
...

The whole statement is MyService.this.stop();, it is not just this.stop() which would be no difference to stop() alone in this case. This notation - MyService.this - is used inside enclosed (nested) classes to denote the enclosing instance, the instance of MyService in this case. See Java Language Specification 15.8.4. Qualified this.

This notation is only needed if the enclosed class has a member with the same name/signature as the enclosing class. In this case, if the method had a different name, stopService for example, there would be no need for a qualified or simple this at all.

CodePudding user response:

this means this instance (in the scope). So, if the stop or the start method is meant to stop or to start a MyService instance, it should be non-static.

  •  Tags:  
  • java
  • Related