c# - Hide an Object's Type from Compiler -
i asked question in interview. caught me off guard.
you have super class , subclass. class b
subclass of a
. both classes have implementation of same function foo()
.
is possible write piece of code makes compiler doesn't know type of object is? in case object b
below.
a b = new b();
then function call in type won't known until execution.
this answer on whiteboard: (a)b.foo();
in c# use dynamic
keyword achieve dynamic typing.
public void mymethod(dynamic myvar) { // compiler don't know exact type of myvar // myvar have foo() method? if not, runtime error. myvar.foo(); }
however, don't think answer looking since a
, b
mentioned (and should apply both java , c#).
what might have been looking (and saying yourself) this:
public void mymethod(a a) { a.foo(); // foo() method called? 1 or 1 b? }
you can use instances of a
, b
parameter mymethod
, because b
have is-a relationship (it inherits) a
. compiler sees a
instance of a
though might instance of b
.
what foo()
method called? depends on whether b
overrides a
's implementation of foo()
or hides it. if hides a
's method called , determined @ compile time , doesn't matter type a
have.
if overrides foo()
(which case) determined @ runtime. since compiler doesn't know exact type of a
, correct method call looked @ runtime based on runtime type of a
.
so compiler do know type (it is-an a
), not know exact type (is subclass or not?).
as side note. (a)b.foo();
cast value returned foo()
a
. if want cast b
a
before calling foo()
should add set of parentheses: ((a)b).foo();
. however, cast unnecessary, since b
declared a
variable (a b = ..
).
Comments
Post a Comment