Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

default inclusion of call to super's cosntructor

 
Imtiaz Nizami
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We know that if we implement a constructor for a Class, Java do not create the default one. We also know that if a subclass constructor is called, constructor chaining happens and the superclass's constructor is called.=

Say we have Class A and Class B. B is the subclass of A.

public class A {
int size;
public A (int mySize) {
size = mySize;
}
}

public class B extends A {
public B {
}
}

If B does not explicitly calls super with the correct parameters, how can Java compiler put in a super call which is NOT no-arg - we know that no no-arg constructors exist for Class A.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your class B won't compile, for exactly the reason you give. B must explicitly call A's constructor and provide the argument.
 
Imtiaz Nizami
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I did try compiling it myself but wanted to make sure with more experienced Java programmers.
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A simple rule with constructors is that if your code compiles, then a constructor is going to be called at each level of the class hierarchy. A constructor will be called at the level of the concrete class that you are instantiating and then at each the level of every class that is inherited -- even in abstract classes (but not in interfaces).

There is a way to prevent a constructor from being called and that is to create a private constructor, but if you don't call the private constructor, the class cannot be instantiated at all (such as the Math class).

Kaydell
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic