Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

default inclusion of call to super's cosntructor  RSS feed

 
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.
 
author and iconoclast
Posts: 24203
40
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.
 
Ranch Hand
Posts: 693
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
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!