Java执行流程 - 重写方法首先执行,而不是构造函数

Bnr*_*rdo 10 java debugging

我在同一个java文件中有以下代码.

import javax.swing.SwingUtilities;
import java.io.File;

public class MainClass2{
   public static void main(String[] args){
       SwingUtilities.invokeLater(new Runnable(){
             public void run() {
                 javax.swing.JFileChooser jfc = new MyFileChooser();
                     File file = jfc.getSelectedFile();
             }

      });
   }
}

class MyFileChooser extends javax.swing.JFileChooser{
    public MyFileChooser(){
        System.out.println("constructor call");
    }
    @Override
    public java.io.File getSelectedFile(){
        System.out.println("call to getSelectedFile");
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,输出给了我

call to getSelectedFile

constructor call

call to getSelectedFile

输出不应该是

constructor call

call to getSelectedFile

我正在使用java 5.

NPE*_*NPE 8

MyFileChooser的构造函数相当于:

public MyFileChooser() {
    super(); // ***
    System.out.println("constructor call");
}
Run Code Online (Sandbox Code Playgroud)

第一次调用getSelectedFile()是由MyFileChooser基类构造函数构成的,它在***上面标记的点之前隐式调用System.out.println("constructor call").

这是堆栈跟踪:

MyFileChooser.getSelectedFile() line: 16    
AquaFileChooserUI.installComponents(JFileChooser) line: 1436    
AquaFileChooserUI.installUI(JComponent) line: 122   
MyFileChooser(JComponent).setUI(ComponentUI) line: 670  
MyFileChooser(JFileChooser).updateUI() line: 1798   
MyFileChooser(JFileChooser).setup(FileSystemView) line: 360 
MyFileChooser(JFileChooser).<init>(File, FileSystemView) line: 333  
MyFileChooser(JFileChooser).<init>() line: 286  
MyFileChooser.<init>() line: 11 
Run Code Online (Sandbox Code Playgroud)