闭门造车姚师傅

Polymorphism, the perspective of construct

字数统计: 252阅读时长: 1 min
2017/05/27 Share

When polymorphism meet initialization of an object, what will happen.

Here is a pretty strange but reasonable example.

A piece of code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Created by boileryao on 5/27/2017.
* Class: PolyConstructor
*/
public class PolyConstructor {
public static void main(String[] args) {
new ColorfulCircle("Blue");
}
}

class Circle {
void draw() {
System.out.println("Circle");
}

Circle() {
System.out.println("Circle, Before drawing");
draw();
System.out.println("Circle, After drawing");
}
}

class ColorfulCircle extends Circle {
String color;
@Override
void draw() {
System.out.println("ColorfulCircle: " + color);
}


ColorfulCircle(String color) {
this.color = color;
System.out.println("ColorfulCircle, Before drawing");
draw();
System.out.println("ColorfulCircle, After drawing");

}
}

Output of the code

Output:

1
2
3
4
5
6
Circle, Before drawing
ColorfulCircle: null
Circle, After drawing
ColorfulCircle, Before drawing
ColorfulCircle: Blue
ColorfulCircle, After drawing

Explanation

Dynamic binding of method

​ Polymorphism, the parent’s method overrided by subclass before the construction of an object.

Construct of a object:

  • execute a sizeof() like operation to determine the memory needed, the set the allocated memory to ZERO.

    Here is the size of ColorfulCircle, containing field ‘color’.

  • Go upward to Object.class, then go down according the inherit level. Execute every class’s constructor to make the object more specific.

    Here, the inherit level is Object -> Circle -> ColorfulCircle, so make the allocated memory a Object first, then Circle, finally ColorfulCircle. Each step only do its own affair, other fileds owner by more specific classes will remain uninitialized(ZEROS, that is null for objects, 0 for numbers, false for boolean etc).

CATALOG
  1. 1. A piece of code
  2. 2. Output of the code
  3. 3. Explanation