• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

Need help on explanation of constructor rules  RSS feed

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can some give me code examples with explanations for the following last 2 rules.

4. If the parent doesn’t have a no-argument constructor and the child doesn’t define any
constructors, the compiler will throw an error and try to insert a default no-argument
constructor into the child class.

5. If the parent doesn’t have a no-argument constructor, the compiler requires an explicit
call to a parent constructor in each child constructor.

Thanks.
 
Sheriff
Posts: 5931
155
Chrome Eclipse IDE Java Postgres Database Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried writing a few simple classes to test this?  What happens?
 
Saloon Keeper
Posts: 10136
214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those two rules basically mean the same thing. When a class doesn't explicitly define any constructors the Java compiler inserts a default constructor that looks like this:

That means that if you have a superclass that doesn't have a parameterless constructor (because it defined a constructor with parameters), the default constructor of the subclass will cause a compilation error, because super() refers to a constructor that doesn't exist. Therefore, subclasses of classes that don't have a parameterless constructor must explicitly define a constructor that calls the appropriate superclass constructor:
 
No holds barred. And no bars holed. Except this tiny ad:
ScroogeXHTML - the small and fast RTF to HTML converter library
https://coderanch.com/t/707504/ScroogeXHTML-RTF-HTML-XHTML-converter
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!