Java execution process – Rewriting methods execute first than constructors

I have the following code in the same java file

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;
    }
}

When I run it, output it to me

Call getselectedfile

constructor call

Call getselectedfile

Should not output

constructor call

Call getselectedfile

I use Java 5

Solution

The constructor of myfilechooser is equivalent to:

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

The first call to getselectedfile () is created by the base class constructor of myfilechooser, which is in system out. Println ("constructor call") is implicitly called at a location marked * * *

This is a stack trace:

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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>