| Author |
Constructor Issues
|
John Paterson
Ranch Hand
Joined: Mar 12, 2012
Posts: 81
|
|
Hi Guys,
The following code compiles fine:
Fruit class
Apple class
However if I remove the no argument constructor from the Fruit class, I run into problems. I am getting the following error:
constructor Fruit in class fruits.Fruit cannot be applied to given types;
required: java.lang.String
found: no arguments
reason: actual and formal argument lists differ in length
I am not sure why, hope someone can advise. Thanks.
regards
John
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4904
|
|
John Paterson wrote:I am not sure why, hope someone can advise. Thanks.
Since you didn't do it yourself, the compiler
(a) Adds a public no-args constructor to any class that doesn't have any.
(b) Adds super() as the first line of any constructor that doesn't already have a super() call (of any kind).
Therefore, your Apple class actually looks like:Make sense now?
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
John Paterson
Ranch Hand
Joined: Mar 12, 2012
Posts: 81
|
|
Hi Winston Gutkowski
Thanks for the reply. You mean to say super() was actually looking for a no-argument constructor in the Fruit superclass and since it didn't find any it gave that error?
regards
John
|
 |
Jeff Verdegan
Bartender
Joined: Jan 03, 2004
Posts: 6109
|
|
John Paterson wrote:Hi Winston Gutkowski
Thanks for the reply. You mean to say super() was actually looking for a no-argument constructor in the Fruit superclass and since it didn't find any it gave that error?
regards
John
Correct.
Any constructor (except in the Object class) that doesn't explicitly calls super(...) or this(...) as its first statement gets a call to no-arg super() inserted by the compiler. If that super() doesn't exist, it's an error.
Additionally, if you don't provide any constructor at all in your class, then, as Winston explained, the compiler inserts a no-arg constructor that does nothing but call the no-arg super().
|
 |
John Paterson
Ranch Hand
Joined: Mar 12, 2012
Posts: 81
|
|
Hi
Noted. Thanks Jeff Verdegan
regards
John
|
 |
 |
|
|
subject: Constructor Issues
|
|
|