Recently I was playing around with some simple Java code using main
methods to quickly test the code I wrote. I ended up in a situation where I had two classes similar to those:
public class A {
public static void main(String[] args) {
// code here
}
}
public class B extends A {
public static void main(String[] args) throws IOException {
// code here
}
}
I was quite surprised that the code stopped compiling and Eclipse complained that Exception IOException is not compatible with throws clause in A.main(String[])
.
Well, both methods are static and the main
function in B
is just hiding the one from A
, so I thought that there is completely no relation between them. In static methods we have no polymorphism and the call is bound to the concrete method implementation during the compilation, therefore I cannot understand why main
in B
cannot throw exception that is not declared in main
signature in A
.
Why Java designers decided to enforce a constraint like this and in what situations it would cause problems if the constraint was not enforced by the compiler?
See Question&Answers more detail:os