Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When initialising any class in java, does it create two objects?

Tags:

java

I am aware that for every class initialization, each class will extends the object class. Does this mean the JVM will create an object for a custom class and the Object class? Can anyone explain this process of initialization of class very clearly.

Edit :

So if I extend any super class to subclass, does this super class occupies the same memory of subclass?

like image 776
developer Avatar asked Jul 23 '13 07:07

developer


People also ask

How does initialization work in Java?

In Java, an initializer is a block of code that has no associated name or data type and is placed outside of any method, constructor, or another block of code. Java offers two types of initializers, static and instance initializers. Let's see how we can use each of them.

Can we create two objects for one class?

A class can be thought of as a "type", with the objects being a "variable" of that type. Multiple objects, or instances of a class can be created in a single HLU program, just as you declare multiple variables of the same type in any program.

How objects are initialized in Java?

In Java, the new keyword is used to create new objects. Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor.

Can we create two objects in Java?

We can create multiple objects of a single class in Java. Note: Fields and methods of a class are also called members of the class.


1 Answers

Does it means JVM will create object for custom class and Object class?

No, it will only create an object for the custom class, but this object contains the Object class members (and the members of all other super classes).

Conceptually, you can think of the memory layout of one instance of custom class looking like this:

+============+
|Members of  |
|Object      |
+------------+
|Members of  |
|other super |
|classes     |
|  ...       |
+------------+
|Members of  |
|Custom class|
+============+

Essentially, there will be one block of memory allocated with the size of the custom class (which includes Object and all other super classes), and by calling the constructors for each of the super classes, the members of the super classes will be initialized.

See also

  • @The New Idiot's link to the JLS for an official reference.
  • Java Objects Memory Structure for some additional information.
like image 63
Andreas Fester Avatar answered Oct 18 '22 08:10

Andreas Fester