Explicit member method reference in Java
-
14-07-2021 - |
質問
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.
解決
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.
他のヒント
The good practice is to favour composition over inheritance: don't extend JFrame
but delare a JFrame yourFrame;
member in your class instead. Then you call the JFrame methods naturally with:
yourFrame.someMethod();
ps: and call your GUI methods from the EDT:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
yourFrame = new JFrame("JFrame example");
initFrame();
yourFrame.setVisible(true);
}
}
}
as other said in the comments you could use this.setwatever()
. usually it is considered a good practice to use this.membervariable
but never really came accross code using this.method().but it works perfectly fine.