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.
Advantages of Method Overriding Method overriding helps in writing a generic code based on the parent class. It provides multiple implementations of the same method and can be used to invoke parent class overridden methods using super keyword. It defines what behavior a class can have.
Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. It allows for a specific type of polymorphism (subtyping).
Constructor Overriding is never possible in Java. This is because, Constructor looks like a method but name should be as class name and no return value. Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding.
Rules for Method Overriding For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden.
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).<init>(File, FileSystemView) line: 333
MyFileChooser(JFileChooser).<init>() line: 286
MyFileChooser.<init>() line: 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With