• Post Reply Bookmark Topic Watch Topic
  • New Topic

Base Class , Super class constructors ****  RSS feed

 
madhup narain
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is it not compiling ...



Can anyone summarize the rules .. i got confused after i read from Khalid
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every subclass constructor must contain a call to a superclass constructor. If you don't put one in yourself, the compiler inserts

super();

This results in a compiler error if the superclass doesn't have a no-argument constructor. In this case, you have to call one of the existing constructors yourself; i.e.,

super(0);

Remember that if you don't define any constructors in a class, the Java compiler inserts one like this:



And so again, this won't compile if the superclass doesn't have a default constructor.

Finally, note that if a class does have one or more constructors defined, the compiler will not add a no-argument constructor.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to write something like this:

The rule is that constructors in derived classes (everything except Object) will do exactly one of the following three things:
1. explicitly call a constructor of the super class super(args) (as in my example).
2. Alternate constructor invocations: this(args). They are used to invoke an alternate constructor of the same class.
3. Nothing explicit -- in which case it's as if you have written super(); as the first statement in your constructor. If your super class doesn't have an accessible no-argument constructor (perhaps none was written (your case) or the one written has private access or our derived class is in another package and the no-arg constructor has package level access) then what you've got is a syntax error: you are implicitly calling a non-existentant or inaccessible constructor. What should you do? Either explicitly call a constructor that does exist (my example) or write an accesssible no-arg constructor for the base class or make the existing one more accessible, say protected.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!