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

本文探讨了Java Swing中JFileChooser的构造与getSelectedFile()方法的调用顺序问题。在Java 5环境下,发现getSelectedFile()在构造函数之前被调用,这导致了预期输出的改变。通过分析代码和调用栈,揭示了这一现象的原因。
摘要由CSDN通过智能技术生成

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, the output gives me

call to getSelectedFile

constructor call

call to getSelectedFile

Shouldn't the output be

constructor call

call to getSelectedFile

I'm using java 5.

解决方案

MyFileChooser's constructor is equivalent to:

public MyFileChooser() {

super(); // ***

System.out.println("constructor call");

}

The first call to getSelectedFile() is made by MyFileChooser's base class constructor, which is invoked implicitly at the point marked *** above, before the System.out.println("constructor call").

Here is the 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).(File, FileSystemView) line: 333

MyFileChooser(JFileChooser).() line: 286

MyFileChooser.() line: 11

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值