Here are two classes,
class A
{
}
class B extends A
{
}
and A is inherited from B.What confuses me is that How many objects were created when I use the following code
A a = new B();
I know when I create an instance of B ,it will first call A's constructor and then call the constructor of B's.
Was there an instance of A been created when call A's constructor?
How many objects were created in
A a = new B();
It creates a single object, which is an instance of B
. It's already a B
when the A
constructor executes, as you'll see if you change your code to:
class A {
public A() {
System.out.println(getClass());
}
}
class B extends A {
}
...
A a = new B(); // Prints B in the A constructor
Basically, the constructor isn't what creates an object - it's what initializes an object in the context of that class.
So you can think of the steps as:
(with constructor chaining up the inheritance tree evaluating constructor arguments, of course... while the constructors are sort-of called going up the chain too, as the first part of any constructor has to chain to the same class or a superclass, the main part of the constructor body happens top-down).
For rather more detail about exactly what happens, see JLS 15.9.4 and JLS 12.5.
See more on this question at Stackoverflow