java - overload and override which throws exception -
public class { public float foo(float a, float b) throws ioexception { } } public class b extends { ...... }
which functions can placed in b class, , why?
- float foo(float a, float b){...}
- public int foo (int a, int b) throws exception {...}
- public float foo(float a, float b) throws exception {...}
- public float foo(float p, float q) {...}
my opinion: 1. wrong, doesn't start public 2. correct, overloading 3. wrong, overriding can't throw broader exception 4. wrong, overriding can't throw broader exception
the general principle governing allowed or not in override can't break java's ability use instance of subclass in context declared type supertype.
float foo(float a, float b){...}
incorrect because cannot reduce visibility of method in subclass. (if allowed, happen @ runtime if called foo
on a
declared a = new b();
?)
public int foo (int a, int b) throws exception {...}
correct.
if override, incorrect because can't use incompatible return type. (you can change return type, return type in override must subtype of return type in overridden)
however, since argument types different, overload, not override ... , correct!
public float foo (float a, float) throws exception {...}
incorrect because cannot throw broader (checked) exception. can change exception(s) must subtype exceptions in subclass. (the point subclass method must not allowed throw checked exceptions superclass methods signature says can't thrown.)
public float foo(float p, float q) {...}
correct. override method can omit thrown exception declarations thrown in overridden method. (it doesn't break checked exception rules if subclass method can't throw , exception superclass method could.)
Comments
Post a Comment