Search code examples
javaoverridingoverloadingthrow

overload and override which throws exception


   public class A {
        public float foo(float a, float b) throws IOException {
  }
}
    public class B extends A  {
           ......
    }

Which functions can be placed in B class, and why?

  1. float foo(float a, float b){...}
  2. public int foo (int a, int b) throws Exception {...}
  3. public float foo(float a, float b) throws Exception {...}
  4. public float foo(float p, float q) {...}

my opinion: 1. wrong, doesn't start with public 2. correct, overloading 3. wrong, overriding can't throw broader exception 4. wrong, overriding can't throw broader exception


Solution

  • The general principle governing what is allowed or not in an override is that you can't break Java's ability to use an instance of the subclass in a context where the declared type is the supertype.

     float foo(float a, float b){...}
    

    Incorrect because you cannot reduce the visibility of the method in the subclass. (If it was allowed, what would happen at runtime if someone called foo on a declared as A a = new B(); ?)

     public int foo (int a, int b) throws Exception {...}
    

    Correct.

    If this was an override, it would be incorrect because you can't use an incompatible return type. (You can change the return type, but the return type in the override must be a subtype of the return type in the overridden)

    However, since the argument types are different, this is an overload, not an override ... and it is correct!

     public float foo (float a, float) throws Exception {...}
    

    Incorrect because you cannot throw a broader (checked) exception. You can change the exception(s) but they must be subtype exceptions in the subclass. (The point is that the subclass method must not be allowed to throw checked exceptions that the superclass methods signature says can't be thrown.)

    public float foo(float p, float q) {...}
    

    Correct. An override method can omit thrown exception declarations that are thrown in the overridden method. (It doesn't break the checked exception rules if the subclass method can't throw and exception that the superclass method could.)