so8857
so8857

Reputation: 351

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!

Upvotes: 2

Views: 1134

Answers (2)

nanofarad
nanofarad

Reputation: 41281

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).

Upvotes: 1

Vic Seedoubleyew
Vic Seedoubleyew

Reputation: 10536

What you wrote is roughly correct.

To be more precise: "invokes the class/constructor" is not entirely correct. A a = new A(); intends to invoke the constructor (invoking a class doesn't mean anything).

Though constructors are not methods, you can think of them a bit like methods: if your class has defined a method like so :

public void myMethod(String s) { ... }

Then trying to call myMethod() without any argument would fail. It's the same here.

Upvotes: 1

Related Questions