HaxeDoc2

(やまだぃちぅ) #1

  • the classBasewhich has a methodmyMethodand a constructor,

  • the classChildwhichextends Baseand also has a methodmyMethodbeing declared
    withoverride, and

  • theMainclass whosemainmethod creates an instance ofChild, assigns it to a variable
    childof explicit typeBaseand callsmyMethod()on it.


The variablechildis explicitly typed asBaseto highlight an important difference: At
compile-time the type is known to beBase, but the runtime still finds the correct methodmyMethod
on classChild. It is then obvious that the field access is resolved dynamically at runtime.

4.3.2 Effects of variance and access modifiers.....................


Overriding adheres to the rules of variance (3.4). That is, their argument types allowcontravari-
ance(less specific types) while their return type allowscovariance(more specific types):
1 class Base {
2 public function new() { }
3 }
4
5 class Child extends Base {
6 private function method(obj:Child):Child {
7 return obj;
8 }
9 }
10
11 class ChildChild extends Child {
12 public override function
13 method(obj:Base):ChildChild {
14 return null;
15 }
16 }
17
18 class Main {
19 static public function main() { }
20 }


Intuitively, this follows from the fact that arguments are “written to” the function and the
return value is “read from” it.
The example also demonstrates how visibility (4.4.1) may be changed: An overriding field
may bepublicif the overridden field isprivate, but not the other way around.
It is not possible to override fields which are declared asinline(4.4.2). This is due to the
conflicting concepts: While inlining is done at compile-time by replacing a call with the function
body, overriding fields necessarily have to be resolved at runtime.

4.4 Access Modifier


4.4.1 Visibility.......................................


Fields are by defaultprivate, meaning that only the class and its sub-classes may access them.
They can be madepublicby using thepublicaccess modifier, allowing access from anywhere.
Free download pdf