aspose file tools*
The moose likes Java in General and the fly likes Constructor Issues Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Constructor Issues" Watch "Constructor Issues" New topic
Author

Constructor Issues

John Paterson
Ranch Hand

Joined: Mar 12, 2012
Posts: 135
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: 8427
    
  23

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?
Articles by Winston can be found here
John Paterson
Ranch Hand

Joined: Mar 12, 2012
Posts: 135
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
    
    6

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: 135
Hi

Noted. Thanks Jeff Verdegan

regards
John
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructor Issues