Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many objects are created due to inheritance in java?

Let's say I have three classes:

class A {     A() {         // super();          System.out.println("class A");     } } class B extends A {     B() {         // super();          System.out.println("class B");     } } class C extends B {     public static void main(String args[]) {         C c = new C(); //Parent constructor will get called     } } 

When I create an instance of class C, it calls the constructor of super class. So, is there more than one object that is getting created? If only one object is created, then how is super() like another class' constructor? Does super() method internally create an object? What I know is, the constructor is also a method (I may be wrong).

My questions are:

  1. How many number of Object is created in this case?
  2. If one object is created then how does Super() internally call the parent class constructor?
like image 514
Java_begins Avatar asked Jul 26 '13 09:07

Java_begins


People also ask

How many objects can be created in Java?

In Java, we can create objects with 6 different methods which are: By new keyword. By newInstance() method of Class class. By newInstance() method of constructor class.

Can we create object of inheritance in Java?

In inheritance, subclass acquires super class properties. An important point to note is, when a subclass object is created, a separate object of a superclass object will not be created. Only a subclass object is created that has superclass variables.

Which class object is created in inheritance?

The class from which the subclass is derived is called a superclass (also a base class or a parent class). Excepting Object , which has no superclass, every class has one and only one direct superclass (single inheritance).

How do you create an inheritance object?

getClass(). getName()); //to know the class of which object is created. } public static void main(String[] args) { InheritanceObjectCreation obj = new InheritanceObjectCreation(); // object creation. } }


2 Answers

  1. There will be one and only one object will be created and ie. A object.

  2. You can imagine like when class A extends B, then all methods and variables are copied to class A.

like image 20
pankaj Avatar answered Sep 23 '22 11:09

pankaj


Great question. What you are probing is how Java initializes objects - and there are a number of steps involved.

i know is constructor is also a method (Maybe i am wrong).

Nearly right. The Constructor is a special method. If you decompile a class file, you'll see the constructors get renamed to <init>. <init> is treated differently from other methods and, for example, can't be called explicitly except through use of the keyword new or super. This is so fundamental that it is implemented in the JVM itself rather than being something defined in the Java language.

How many number of Object is created in this case.

One object is created - an instance of C.

C is additionally and simultaneously an instance of B and an instance of A and also Object.

If one object is created then how internally super() is calling Parent class Constructor . How Super is able to call parent class constructor.

This is where we get into initialization - initialization is how the JVM creates a new instance of an object and sets all the member values - those of the specific class and those of the superclasses. There are several stages involved:

  • Load all the referenced classes and initialize those classes. Class initialization is itself non-trivial so I won't cover it here. It is well worth reading up.
  • Allocate a chunk of memory for holding the members of the instance, which will include the all members of A, B and C. NOTE this explains one aspect of your question: how can the constructors of the base class and its subclasses update or refer to the same object - all the members of the instance from all classes are stored one after the other in the same chunk of memory.
  • Initialize all the members to their default value. For example, int and float members will be set to 0 and 0.0f.
  • Execute or calculate the member initializers, eg:

    private int a = 10; private int b = a * 5; private String c = Singleton.getInstance().getValue(); 
  • Note (1) that member initialization occurs strictly in the order that members are declared in the class. This means that references to members later in the declaration are broken:

    private int a = b * 5; // Forward reference; won't compile private int b = 10; 
  • Note (2) that there is a under-used facility in Java to run arbitrary code to initialize values before the constructor is executed. These code blocks are executed at this time again strictly in order of declaration:

    private int a; private int b = 1; {     // Initization occurs after b but before c.     // c cannot be referenced here at all     int i = SomeClass.getSomeStatic();     a = i * 2; } private int c = 99; 
  • Execute the constructor of C. Constructors must either directly invoke a constructor from the superclass or the compiler will automatically add super() as the first line of the constructor. This means that the constructors are strictly executed in order:

    1. Object
    2. A
    3. B
    4. C

The object is now initialized and is ready for use. You can do some dangerous stuff if you initialize value using instance methods:

public class Wrong {     int a = getB(); // Don't do this!     int b = 10;     public int getB() {          return b;     } } 

Here, a is initialized to 0. This is because, at the point getB() is invoked, Java has cleared the value of b to the default (0), but has not yet set it to 10 in the second phase of initialization.

In summary - there is only one object and it is created and initialized in a number in stages. During those stages, the object is, by definition, not completely defined.

like image 85
Andrew Alcock Avatar answered Sep 26 '22 11:09

Andrew Alcock