• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

The Implicit Constructor

 
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's fact that Java allows classes to be programmed without attributes, though it can never be created without methods - if it is, a constructor is provided. Who is responsible for creating the empty constructor when another is not available?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The Java compiler creates it. It's possible to engineer a .class file which contains no such constructor, and it will be a perfectly legal class file. The default constructor is just part of the Java language spec.
 
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I hope I'm not being to "nit-picky", but I like to use the term "default constructor" rather than "empty constructor" because no constructor is truly empty.
Java (compiler) does two things for you regarding constructors. First, if you have a class with no constructors defined it will create a constructor that takes no parameters.
Second, if it finds a constructor that doesn't explicitly invoke another constructor (either in the same class or the parent class), it adds "super();" as the first instruction in the constructor.
So the default constructor for "MyClass" ends up being:

The reason this is important it it helps explains why the following doesn't compile.

Since "Child" doesn't have a constructor the compiler will create one and add a call to "super()" as the only statement. However the parent class doesn't have a default constructor, so it then issues a compile error on the very line which it added. And it's a fairly cryptic error message which doesn't make much sense unless you know what is going on behind the scenes.
I know, more information than you asked for ... my apologies ...
 
reply
    Bookmark Topic Watch Topic
  • New Topic