Search code examples
javadefault-constructor

Invoking the default constructor (in Java) in a class that only has a defined constructor that requires parameters


Please tell me if I have the proper understanding of the following code:

public class Test {
  public static void main(String[] args) {
    A a = new A();
    a.print();
  }
}

class A {
  String s;

  A(String s) {
    this.s = s;
  }

  void print() {
    System.out.println(s);
  }
}

The line “A a = new A();” invokes the class/constructor to create a new object with reference variable “a”. Class A has a defined constructor that requires a string argument, thus it does not have the default constructor. This means that the instantiation without any string arguments causes a compiler error.

If I were to add a string argument into the instantiation, e.g. A a = new A("goldfish"); the program would compile and run.

I am not sure if I have used the right vocabulary for this, so feel free to correct anything that is inaccurate/confusing. Thanks!


Solution

  • Your understanding is pretty much correct. The one thing that I would change is "create a new object" to "create a new instance of A" with a reference to a java.lang.String in parameter s. In this case the constructor assigns that parameter to a field, but it can do something else with it entirely (such as use it to calculate a different value for some field).