Search code examples
javacoding-stylecode-readability

Explicit member method reference in Java


Based on the following example :

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class ExempleJFrame extends JFrame {

    public ExempleJFrame() {
        super("JFrame example");
        setLocation(50, 50);
        setSize(200, 200);
        getContentPane().add(new JLabel("This is a text label!", SwingConstants.CENTER));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        ExempleJFrame frame = new ExempleJFrame();
        frame.setVisible(true);
    }

}

Is there a way to make it more explicit that I am calling a member method (see setLocation() and setSize())?

I am looking for something in the lines of this.setLocation() to make it explicit that I call a member method and not something from outer space.


Solution

  • If you're using Eclipse, you can set a Save Action (Additional Save Actions -> Member Accesses -> Use 'this' qualifier for method accesses'), which will automatically convert setLocation to this.setlocation on save.

    Personally I don't find it particularly useful, because a non-prefixed method call can only be either

    • a static method call (which will be italic in Eclipse)
    • a this member call
    • a super member call

    The last two rarely need to be distinguished IMHO, because of run time dispatch.