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?

  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 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

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -