vrogros
vrogros

Reputation: 25

object creation in java behind scenes (java object instantiation)

I understand that there are three parts to object creation:

  1. Declaration
  2. Instantiation
  3. Initialization

classA{}
classB extends classA{}
classA obj = new classB(1,1);

Instantiation

It has to create an object using new operator and this object must have all the fields related to classB (initialized to default values does this step give a call to default constructor?) this is instantiation does it mean this step is initialization using java's default constructor?

Initialization

this object is then passed down the hierarchy giving calls to various constructor in the way to get initialized (which comes under initialization) and the final obj is created by 'classB(1,1)` constructor whith required Initializations

but how is the object mentioned in instantiation step being created initially with all available fields?

please point out if anything i said is wrong

Upvotes: 0

Views: 411

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234857

Roughly, the way it works is:

  1. The new bytecode instruction is executed with a symbolic reference to the class of the object to be created. As described in the Java Virtual Machine Specification, this allocates a new object in the garbage collected heap and initializes all fields to their default values.
  2. One of the object's constructors is called. (Which one is called depends on what was coded.) All constructors (except for Object itself) must, as their first step, call another constructor in the same class or call a constructor in the superclass. (If you don't code one of these calls in a constructor, the compiler automatically inserts a call to super();—the default superclass constructor—at the start of that constructor. Each constructor in the chain—starting with Object at the deepest level of constructor calls—does whatever setting of instance fields in the object.

The second step might be modified slightly if there are instance initializers in the class declaration. See Chapter 8 of the Java Language Specification for details.

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109613

If the class has no constructor a default constructor is implicitly defined. Constructors have method name <init> in a stacktrace.

A constructor call does the following:

  1. the object is created, with all fields nulled: 0, 0.0, null, ...
  2. the super constructor is called, possibly implicit if not present in the code.
  3. all initialized fields (A a = ...;) are initialized by doing the assignments.
  4. the rest of the constructor is executed.

Upvotes: 2

Related Questions