This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Compiler error overriding static methods

 
Greg George
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that you can't override static methods. But then why does the compiler generate the following error when attempting to compile the code shown? If there is no overriding going on then the thrown exception should be irrelevant. Am I missing something here?

--------------------------------------------------------------
> ORTest.java:21: staticMethod() in ORTest cannot override staticMethod() in Base;
> overridden method does not throw java.io.IOException
> public static void staticMethod() throws IOException
> ^
> 1 error
--------------------------------------------------------------
import java.io.*;

class Base
{
public static void staticMethod()
{
System.out.println("In Base.staticMethod()");
}
}

public class ORTest extends Base
{
public static void main(String[] args)
{
try
{
ORTest.staticMethod();
Base.staticMethod();
}
catch (IOException e)
{
}
}

public static void staticMethod() throws IOException
{
System.out.println("In ORTest.staticMethod()");
}
}
 
Carol Enderlin
drifter
Ranch Hand
Posts: 1364
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the Java Language Specification says so:

8.4.6.3 Requirements in Overriding and Hiding
...
Moreover, a method declaration must not have a throws clause that conflicts (�8.4.4) with that of any method that it overrides or hides; otherwise, a compile-time error occurs.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only practical difference between instance method overriding and class method hiding is that instance method calls select the method to invoke based on run time polymorphism.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic