Constructor call - java

I have three classes:
public class A {
public A(){
System.out.println("in A");
}
}
public class B extends A{
public B(){
System.out.println("in b");
}
}
public class C extends B{
public C(){
System.out.println("in C");
}
}
Now I am really not sure how the constructor calls work.
If I instantiate C c= new C();, in what order (and why that order) does the constructors get called.
If I instantiate the class C, then should not it just check if the class C has got any constructor or not and if it does, it shall use it?
Why does it output-> In A In B In C?
Doesn't it go up in the hierarchy only when it doesn't find the constructor in it's own class? Or the constructors of the super class are called implicitly every time?

Super constructor are called by default from the base class constructor.
The only case in which you should call a super class constructor with super, is when you need to explicitly pass a parameter to the super class constructor itself.
So the answer is yes, they are all called. The order is from the most up class in the hierarchy down to the base class, so : A, B, C.

Default constructors are always invoked, and are invoked top-down - from the topmost super-class to the lowest base-class.
Note that the super(...) call is necessary only for parameterized constructors. In your case you don't have any, so the default gets called automatically.

When a constructor is invoked, it first calls super(), so though the stack trace will show: C->B->A, actually A will be invoked first and C will be invoked last, thus the printing will show:
in A
in B
in C

super() is implicit, as the default constructors if no constructors declared.
The constructors run upwards:
C calls B, B calls A, A calls to Object that does nothing and return to A, then outputs and return the flow to B, that outputs and return to C that outputs.

Super constructor is called by default. It is executed prior to any lines of code in the derived class's constructor. So if you call new C(), A's constructor is run, then B's, then anything in C's.

Yes when you not define any constructor it will implicitly create the default construct and call it. Now when you extends any class then like class C it go with its constructor but there it didn't find to call the super class explicitly so the compiler implicitly call the super class constructor. that why when we call the super class constructor that statement always first like this way
public C(){
super();
}
if you write any statement before calling the super class constructor you getting error

Take a look at the Java language specification
"If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments."
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#41652

Class A is the super class for B and class B is super class of C. That means A is at the top position among them, where B is in top for C, next to A and C is sitting bottom of B. So class A execute first and then B and then C. It's like some priority in Java for super classes.

Related

Does the JVM internally instantiate an object for an abstract class?

I have an abstract class and its concrete subclass, when I create an object of subclass it automatically calls the super constructor. Is the JVM internally creating an object of the abstract class?
public abstract class MyAbstractClass {
public MyAbstractClass() {
System.out.println("abstract default constructor");
}
}
public class ConcreteClass extends MyAbstractClass{
public static void main(String[] args) {
new ConcreteClass();
}
}
then how constructor exists without an object in JVM ?? (In case of abstract class)
Also constructor gets executed after object is being created then without creating the object of abstract class how the default constructor get executed ?? (This is mentioned in Java Doc)
Is it true that you can't instantiate abstract class?
Yes.
Is JVM internally create object of abstract class ?
No, but it's a common misunderstanding (and that wouldn't be an unreasonable way for it to be done; prototypical languages like JavaScript do it that way).
The JVM creates one object, which is of the class you created (in your case, ConcreteClass). There are aspects of that one object that it gets from its superclass (MyAbstractClass) and from its subclass (ConcreteClass), but there is only one object.
The object is an aggregate of all of its parts, including parts that seem to have the same name, such as a method of the superclass that is overridden by the subclass. In fact, those methods have different fully-qualified names and don't conflict with one another, which is why it's possible to call the superclass's version of an overridden method.
So if it's just one object, why do you see the call to MyAbstractClass's constructor? Before we answer that, I need to mention a couple of things the Java compiler is doing that you don't see in the source code:
It's creating a default constructor for ConcreteClass.
In that constructor, it's calling the MyAbstractClass constructor.
Just to be thorough: In the MyAbstractClass constructor, it's adding a call to the superclass's (Object) constructor, because there's no super(...) call written within the MyAbstractClass constructor.
Here's what the code looks like with the bits the Java compiler adds for you filled in:
public abstract class MyAbstractClass {
public MyAbstractClass() {
super(); // <== The Java compiler adds this call to Object's constructor (#3 in the list above)
System.out.println("abstract default constructor");
}
}
public class ConcreteClass extends MyAbstractClass{
ConcreteClass() { // <== The Java compiler adds this default constuctor (#1 in the list above)
super(); // <== Which calls the superclass's (MyAbstractClass's) constructor (#2 in the list above)
}
public static void main(String[] args) {
new ConcreteClass();
}
}
Okay, with that out of the way, lets touch on a point TheLostMind very usefully mentioned in a comment: Constructors don't create objects, they initialize them. The JVM creates the object, and then runs as many constructors (they really should be called initializers) against that one object as necessary to give each superclass a chance to initialize its part of the object.
So in that code, what happens (and you can step through this in a debugger to fully understand it) is:
The JVM creates an object
The ConcreteClass constructor is called
The first thing that constructor does is call its superclass's constructor, in this case MyAbstractClass's constructor. (Note that this is an absolute requirement: The Java compiler will not allow you to have any logic in the constructor itself prior to the superclass constructor call.)
The first thing that constructor does is call its superclass's constructor (Object's)
When the Object constructor returns, the remainder of the MyAbstractClass constructor runs
When the MyAbtractClass constructor returns, the remainder of the ConcreteClass constructor runs
The object is returned as the result of the new ConcreteClass() expression.
Note that the above would get more complicated if there were instance fields with initializers. See the JLS and JVM specs for the full details.
JVM doesn't create object of abstract class. it is calling its super constructor
JVM will create one object, an instance of the concrete class which inherits fields and methods of abstract class

How many objects are created in inheritance? [duplicate]

I have a question about inheritance in Java.
I have two classes A and B , and class B, inherits from A:
public class A {
public A() {
System.out.println("Hi!");
}
}
public class B extends A {
public B() {
System.out.println("Bye!");
}
public static void main(String[] args) {
B b = new B();
}
}
When I run program B, the output is:
Hi!
Bye!
Question : why the constructor of class A is invoked, when I create and object of class B ?
I know that B inherits everything from A - all instance or class variables, and all methods, and in this sense an object of B has all characteristics of A plus some other characteristics defined in B. However, I didn't know and didn't imagine that when I create an object of type B, the constructor of A is also invoked.
So, writing this:
B b = new B();
creates Two objects - one of type B, and one of type A.
This is getting interesting,
can somebody explain why exactly this happens?
It doesn't create two objects, only one: B.
When inheriting from another class, you must call super() in your constructor. If you don't, the compiler will insert that call for you as you can plainly see.
The superclass constructors are called because otherwise the object would be left in an uninitialized state, possibly unbeknownst to the developer of the subclass.
Your subclass actually looks like this after the compiler inserts the super call:
public class B extends A {
public B() {
super();
System.out.println("Bye!");
}
}
It doesn't create 2 objects, it only creates one instance of B. The reason the super class constructor is invoked is because, like you said, B has all of the fields of A, and these fields need to be initialized.
Remember inheritance is an "is a" relationship between the base class and the subclass, thus every time you have an instance of a subclass, by definition you will also have an instance of the base class (as part of the instance, not as two separate instances). To initialize the base class properly the constructor is called.
Additionally, think about what would happen if you subclass depended on some internal state of the base class. Wouldn't you want the instance of the base class to be initialized then?
This is done because the constructor is used to initialize the object. Since B is also an A, it calls the constructor for A first, then the constructor for B.
As a side note, you can use super(arg1, etc) to choose which constructor of A is called based on the parameter types you pass... but it must be the first line in the constructor.
The constructor contains all of the initialization for A. You are not creating two objects. You are creating one object, then running the initializer for the superclass to initialize its members, and then running the initializer for the deriving class to initialize its members.
It does not create two objects, it just creates one object b. b is of type B and of type A. A constructor is basically saying here is what you need to do to construct me. So when you are creating a new "B" instance, you are building an object that is both a B() and an A(). Imagine the following scenario:
class Q {
int i;
public Q() {
// set default value
i= 99;
}
}
class Z extends Q {
public Z() {
}
}
If the constructor for Q WAS NOT called, how would i get its default value?
The creation of B does not create an extra A.
But by creating B, you create a kind of A, because B is a A.
Java/C++ call the constructor of A for your implicitly. Why? Language design. But doing so is fine, because the constructor of A might contain some initializations. And as B uses all the features and bugs of A, these features better be initialized properly.
The constructor of a class is very important concept in most OOP
Classes, by providing state and the means to manipulate that state, allow the easier maintenance of invariants. The constructors role is to get the class into a state that conforms to those invariants (or throws thus forbidding usage of an invliad object).
this is somewhat looser than intended in many languages since the constructor is allowed to pass its own 'this' reference elsewhere but this is at least under the control of the class (as such it can know that it is in a sufficiently stable and valid state for it to be accessible to the rest of the world)
Inheritance makes this complex since B is-a A in a very real sense and thus can invoke any of the methods provided by A. The parts of B that are A should therefore get their chance to initialize themselves before B gets a look in, thus the constructor for A is called before the real work of the B constructor begins.
If A intializes members in it's constructor and you forget to call super in your derived class then the members of A could be in a bad state. Java is trying to stop you from shooting yourself in the foot.
Only one object is created, both contractors are running on the same object.
The reason is simple, as you know B has all the variables and methods of A, so if some variable of A needs initializing so methods of A can work someone has to initialize it - and that someone is A's constructor.
for example:
public class A {
public A() {
x = 1;
}
private int x;
public int getX() {
return x;
}
}
public class B extends A {
public B() {
}
public static void main(String[] args) {
B b = new B();
System.out.println(b.getX()); // should print 1
}
}
When new object is create(B), inside B A object is created(because of extends keywords) . In B class JVM search B class constructor, but due to extends keywords it goes to super class constructor. inside A class x value is initialized. But x is private so that we can access outside class throw getXxx() method and get the result.
When sub class object is created then internally it was not created for super class object.But the memory should be allocated for super class members.
In java when you create an object of child class the constructor of parent class is always called because Object class is the parent of every super class and when you call the constructor of Object class then only your object is created and java does not support multiple inheritance in case of class so if you extends any other class then the relationship between you child class and the Object class is through the Parent class so to call the constructor of the Object class the constructor of Parent class must be called.
Every superclass has a constructor and each constructor up the hierarchy runs at the time an object of a subclass is created.
if super class object is not created then how sub class is accessing super class non static methods and variables.
I studied that non-static methods and variables can be accessed only through objects..

Order of Constructors execution in derived class in Java

I have derived a class in java.
I noticed that the superclass constructor gets called before code in my derived class constructor is executed.
Is there a way to invert that order?
Example:
class Animal
{
public Animal()
{
//do stuff
}
}
class Cat extends Animal
{
int var;
public Cat(int v)
{
var = v;
super();
}
}
This is what I would like to do, but calling super() like that gives an error...
No, there is no way to invert that order. If you explicitly call a parent class constructor you are required to do it at the top of your constructor. Calling it later would allow a child class to access the parent class's data before it's been constructed.
No, you can't invert the order of constructor calls this way. A call to super() must be the first statement in a constructor. And if there is no such call, Java inserts an implicit call to super() as the first statement.
The JLS, Section 8.8.7, states:
The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).
ConstructorBody:
{ [ExplicitConstructorInvocation] [BlockStatements] }
There isn't a way to call run the sub class constructor before superclass constructor. That's basically like trying to create the subclass even before the superclass gets created, which is impossible since the subclass relies on superclass attributes to get created.

Why can't we have this() and super() together in Java? [duplicate]

This question already has answers here:
Why can't this() and super() both be used together in a constructor?
(11 answers)
Closed 5 years ago.
I have this program:
public class A
{
public A(){
System.out.println("I am in A");
}
public static void main(String args[]){
B a = new B("Test");
}
}
class B extends A
{
public B(){
System.out.println("I am in B");
}
public B(String s){
this();
super();
System.out.println("I am in B as " + s);
}
}
Now why can't I call the this constructor of B to invoke the default constructor? This is giving me compile time error.
this and super must be the first line in a constructor.
EDITED:
Language spec
8.8.7. Constructor Body
The first statement of a constructor body may be an explicit
invocation of another constructor of the same class or of the direct
superclass (§8.8.7.1).
this() calls another constructor in the same class.
super() calls a super constructor.If no super() is explicitly written,the compiler will add one implicitly. Hence, you will end up calling super() twice.
So, both are not allowed.
EDIT
In context of your code : remember, super() should always be the first line in a constructor.
Upon further reflection my answer as it was below is basically correct but lacking some nuance. Essentially, you can call a super constructor once. This is to ensure your super class is only constructed once. This means that the first line of a given constructor can be a call to another constructor in the current class or a call to a constructor in the super class. This also means that you can only call another constructor once in any given constructor; you must choose to call one in the current or super class. This ensures that all super classes will be fully constructed before the current object is.
Old explanation:
The fundamental reason is that all super classes must be constructed before the subclass can be. To this end, Java will implicitly call super() if no such invocation exist on the first line of a constructor. The only way to override this behavior is to explicitly call a different constructor in your super class. Basically, Java must create your hierarchy before you can be created.
Putting your constructor first violates this requirement and therefore is illegal.
According to Java this() and super() should be the first statement in constructor.Now the point is we can not write both at once as a first line.If u write this() and not super,dont expect that super will be called implicitly.
It is as simple as it is.U have no option to write them together in single constructor body

What does "constructors are not inherited" exactly mean?

I read somewhere that in Java "constructors are not inherited".
On the other hand, I also read that if I don't explicitly call super, Java automatically calls the super class constructor with no arguments (such a constructor must exist in this case).
Isn't automatically calling the super class constructor (with no arguments) a form of inheritance?
What does "constructors are not inherited" exactly mean?
It means that you cannot create a subclass, using a constructor of the super class-if the subclass did not also declared it. An example;
class A {
A() {}
A(String s) {}
}
class B extends A {
}
Now you cannot do this:
B b = new B("testing");
It means just because your superclass has a contructor doesn't mean the subclass will automatically get the same constructor; you have to define it manually.
The default constructor is kind of an exception and kind of isn't. It's automatically defined for you, but it's not really "inherited" because it's still part of the subclass; it's not a member of the superclass.

Categories