How constructors work
Consider the
class Conexample which has three fields namely speed, cost and name.
It has two
constructors defined. One is a common parameter-less constructor or can also be
called as default constructor, the second one is a parameterized constructor
having two integer parameters.
ConMain is
the name of the main program where the objects of class Conexample are created.
Consider the
following picture which demonstrates the execution and inner processing of
constructors.
STEPS:
(1) Here we create an object of type
Conexample named obj1. When the javac compiler encounters the statement “Conexample obj1” it searches for the
program named Conexample in the present package or in the present memory
location and if the program source file is found it creates a variable obj1 of
type Conexample.
(2) When the compiler encounters the code “new Conexample” the compiler goes to the source file of Conexample
and initializes the members/fields which are present outside of a constructor
or a function.
(3) When the compiler encounters the code “new Conexample()” the compiler invokes the
constructor Conexample() to initialize the fields that are present inside the
constructor body.
(5) The
object obj1 is now assigned to the reference returned by the constructor and
hence points to the object created and initialized by the constructor as shown
in the figure.
Similarly another object obj2 will be created. This comes under a case of parametrized constructor which we shall see in next posts.
Hope this explanation helps. See you again BYE!!





