• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

default no-arg constructor...

 
Ramender Mall
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Why java does not provide default no-arg constructor , ALWAYS....even if we have defined one with arguments?....
what cud be the logic behind this???

ramy
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to use the arguments contructor whenever you extend your class. If you have a "Person" class with name, address, date of birth, then all the functionality for name etc remains in the Person class.
If you then extend it to "Member" with additonal fields of membership number and date of joining, then the name etc remain in the Person class, and your Member class "borrows" any methods which handle those fields. You can't handle them from the Member class unless you override the methods, which defeats the object of having inheritance in the first place.

The super(arg0, arg1, arg2); statement at the beginning of your constructor is a way of getting the data back where they belong, into the superclass. You have to get those data where they belong, otherwise the superclass won't have its data and you can't use either the superclass or the subclass.

So, the compiler insists you put a super(arg0, arg1, arg2); statement at the beginning of your constructor. It is a reminder of how to use inheritance.
 
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moreover, there are some objects that have no sense without a minimal set of parameters.

If there were always a default Constructor, we could imagine something like :

Color c = new Color();
// Which color does c represent ??

File f = new File();
// Ok, but what's the file name here ?

Integer i = new Integer();
// What's i value ?
 
Stuart Ash
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ramender Mall:
Hi all,

Why java does not provide default no-arg constructor , ALWAYS....even if we have defined one with arguments?....
what cud be the logic behind this???

ramy


Look at it this way.

a. Imagine Java did not originally provide a constructor.

b. Now, if you are implementing an argful constructor, it's painful to try to code in a privated default constructor, just to indicate that the argful way is the only way.

c. Now, if you are not implementing any constructor at all, isn't it nice if Java took care. Hence the implicit no-arger.


SO, the bottom line is, either explicitly specify all constructors yourself, or let Java do the default thing.
 
Ramender Mall
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx to all f u....


got it.....
ramy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic