为什么在Java中的方法调用中使用括号?

use*_*986 3 java methods field class instance

虽然我做了一些广泛的搜索,但我遇到了一些代码并且无法理解它的某个方面!

我的问题是:为什么在方法调用的中间使用括号?

    package com.zetcode;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;


    public class QuitButtonExample extends JFrame {

    public QuitButtonExample() {

        initUI();
    }

    private void initUI() {

       JPanel panel = new JPanel();
       getContentPane().add(panel);

       panel.setLayout(null);

       JButton quitButton = new JButton("Quit");
       quitButton.setBounds(50, 60, 80, 30);

       quitButton.addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent event) {
               System.exit(0);
          }
       });

       panel.add(quitButton);

       setTitle("Quit button");
       setSize(300, 200);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                QuitButtonExample ex = new QuitButtonExample();
                ex.setVisible(true);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我指的是getContentPane().add(panel);声明.我知道它的作用,但并不真正理解它是如何工作的.我是Java的新手,并且在OO中有基础知识,比如类字段,类方法,实例字段,实例方法,内部类,但是这个.

Mar*_*nik 9

这就是常见的习语,称为方法链,看起来像.

getContentPane().add(panel);
Run Code Online (Sandbox Code Playgroud)

解析为

Container c = this.getContentPane();
c.add(panel);
Run Code Online (Sandbox Code Playgroud)

parens表示方法调用,其返回值就地用作this下一个方法调用(add)的对象.