Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

The Implicit Constructor  RSS feed

 
Philip Pomario
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • 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?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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.
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • 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 ...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!