Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When instantiating a Java object, is an object of the parent class created automatically?

Suppose I create an object, and one constructor of the parent class is run. With this constructor a new object of the parent is created as well behind the scenes?

If not, where are the private fields of the parent class stored? You can actually call any method of the parent object (with or without super) which operates of the private fields invisible of the calling object.

If anyone who is most familiar with the Java Memory Model, his or her answer is very welcome!

like image 571
kavai77 Avatar asked Oct 11 '13 08:10

kavai77


People also ask

What happens when you instantiate an object in Java?

In Java, instantiation mean to call the constructor of a class that creates an instance or object of the type of that class. In other words, creating an object of the class is called instantiation. It occupies the initial memory for the object and returns a reference.

Is automatically called when an object of a class is created?

A constructor in C++ is a special method that is automatically called when an object of a class is created.

Can you instantiate an object of a parent class?

Following the object oriented methodology, a child class can be instantiated as an object that can inherit the attributes of the parent class. This is the process of inheritance, much like how a benefactor can pass on their wealth or assets to a beneficiary.

What happens when you instantiate an object?

An instance of an object can be declared by giving it a unique name that can be used in a program. This process is known as instantiation. A class can also be instantiated to create an object, a concrete instance of the class.


1 Answers

With this constructor a new object of the parent is created as well behind the scenes?

No, only one instance is created. The created instance contains the attributes of the current class and all of its superclasses.

If not, where are the private fields of the parent class stored?

Like all class attributes they are stored on the heap. There is no difference in terms of memory location if they are defined in the current class or the superclass.

like image 50
Adam Siemion Avatar answered Sep 28 '22 07:09

Adam Siemion