Something interesting about two overloaded constructors of FileInputStream in Java 7 API -
before talking fileinputstream, starting scenario there 2 valid, overloaded methods compiler confused , report compile-time error in response inputs.
here methods.
double calcaverage(double marks1, int marks2) { return (marks1 + marks2)/2.0; } double calcaverage(int marks1, double marks2) { return (marks1 + marks2)/2.0; }
here complete code showing use of methods:
class myclass { double calcaverage(double marks1, int marks2) { return (marks1 + marks2)/2.0; } double calcaverage(int marks1, double marks2) { return (marks1 + marks2)/2.0; } public static void main(string args[]) { myclass myclass = new myclass(); myclass.calcaverage(2, 3); } }
because int literal value can passed variable of type double, both methods acceptable candidates literal values 2 , 3, , therefore compiler fails decide method pick.
this confused when take above concept me, dive further java 7 api fileinputstream class, , study 2 overloaded constructors of class.
- public fileinputstream(string name) throws filenotfoundexception {.....}
- public fileinputstream(file file) throws filenotfoundexception {.....}
according java 7 api source code, definition of version takes string object argument is:
public fileinputstream(string name) throws filenotfoundexception { this(name != null ? new file(name) : null); }
now, if "name" indeed null, this(name != null ? new file(name) : null); evaluates this(null); in turn equivalent invocation of fileinputstream(null); both fileinputstream(string) , fileinputstream(file) become possible choices invoked null value. not give rise ambiguity? so, isn't there compile-time error that?
i understand filenotfoundexception raised, separate issue comes later. how ambiguity resolved before that?
your error here:
now, if "name" indeed null,
this(name != null ? new file(name) : null);
evaluatesthis(null);
in turn equivalent invocation offileinputstream(null);
it evaluates this((file) null)
-- is, null value explicitly typed file
. because expression name != null ? new file(name) : null
has have type, , type specific type of 2 alternatives. in case, 1 alternative typed file
, other typed null
, specific common type file
.
that's why it's able unambiguously resolve fileinputstream(file)
constructor. it's analogous to:
file file = null; new fileinputstream(file);
Comments
Post a Comment