-2

I was wondering what's the difference between the two scenarios. Can some explain or are the same ?

Class MyClass1(){
    String property;
    // has a compiler defined default constructor
    // MyClass1(){ }
}

Vs

Class MyClass2(){
     String property;
     // has a compiler user defined constructor
     MyClass2(){ }
}
PrakashSharma
  • 386
  • 5
  • 16
  • OP is asking because of [this answer](http://stackoverflow.com/a/35117538/3824919) and my comment beneath it (just to provide a small context for this question). – Tom Jan 31 '16 at 18:57

2 Answers2

1

The first case (compiler defined default constructor) occurs if and only if there are no explicit constructors written. It's public if the class itself is public, and requires a no-argument superclass constructor (compiler default or explicit) that is public or protected. JLS

The second option, with a user defined constructor, allows you to actually put initialization code into it. Even if there are no parameters your constructor may still want to do something (for example store the timestamp of when the object was constructed to a field).

Additionally, if you are writing a subclass to this class, and you do not explicitly call a superclass constructor, the no-arg super() constructor will be called. If it doesn't exist, this will throw an error, so you can declare a protected MyClass2(){} to allow the subclass to make that call.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
1

The second example is only instantiatable by classes in the same package (because you have default - or package level - visibility on the constructor). The default constructor will not be added by the compiler because you have an explicit constructor. For them to be equivalent, it would need to have public level visibility like

class MyClass3() {
     String property;
     public MyClass3() {
         super(); // <-- implicit before.
         this.property = null; // <-- also implicit before. 
     }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249