This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor Issues

 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10527
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Noted. Thanks Jeff Verdegan

regards
John
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic