12.5
Creation of New Class Instances
EXECUTION
ColoredPoint() { super(); }
is provided for it automatically by the Java compiler.
This constructor then invokes the
Point
constructor with no arguments. The
Point
constructor does not begin with an invocation of a constructor, so the com
piler provides an implicit invocation of its superclass constructor of no arguments,
as though it had been written:
Point() { super(); x = 1; y = 1; }
Therefore, the constructor for
Object
which takes no arguments is invoked.
The class
Object
has no superclass, so the recursion terminates here. Next,
any instance variable initializers and static initializers of
Object
are invoked.
Next, the body of the constructor of
Object
that takes no arguments is executed.
No such constructor is declared in
Object
, so the compiler supplies a default one,
which in this special case is:
Object() { }
This constructor executes without effect and returns.
Next, all initializers for the instance variables of class
Point
are executed. As
it happens, the declarations of
x
and
y
do not provide any initialization expres
sions, so no action is required for this step of the example. Then the body of the
Point
constructor is executed, setting
x
to
1
and
y
to
1
.
Next, the initializers for the instance variables of class
ColoredPoint
are
executed. This step assigns the value
0xFF00FF
to
color
. Finally, the rest of the
body of the
ColoredPoint
constructor is executed (the part after the invocation
of
super
); there happen to be no statements in the rest of the body, so no further
action is required and initialization is complete.
Unlike C++, the Java language does not specify altered rules for method dis
patch during the creation of a new class instance. If methods are invoked that are
overridden in subclasses in the object being initialized, then these overriding
methods are used, even before the new object is completely initialized. Thus,
compiling and running the example:
class Super {
Super() { printThree(); }
void printThree() { System.out.println("three"); }
}
230
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved