Java 执行流程 - 重写的方法比构造函数先执行

2023-12-24

我在同一个 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;
    }
}

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

call to getSelectedFile

constructor call

call to getSelectedFile

输出不应该是

constructor call

call to getSelectedFile

我正在使用java 5。


MyFileChooser的构造函数等价于:

public MyFileChooser() {
    super(); // ***
    System.out.println("constructor call");
}

第一次致电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 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 执行流程 - 重写的方法比构造函数先执行 的相关文章

随机推荐