-2

Just why are they used? I'm a beginner by the way. I understand default constructors that initialize values because it makes logical sense, but why use a constructor with parameter to say that an instance variable age for example is equal to a. What is the purpose? What happens without it and only the initializer constructor? Other questions asked on here do not make sense tome For example:

public class MyCats {
    private int age;
    private String name;

 public MyCats(int a, String n) {  // why do I need this?
    age = a;
    name = n;
 }

 public MyCats() {
   age = 0;
   name = "";
 }
}
Janie
  • 29
  • 2
  • 9
  • Consider an object which requires values to be set in order to be meaningfully constructed. In such a case you'd want a parameterized constructor and no non-parameterized constructor, so consuming code would be required to provide the values. – David Feb 09 '19 at 23:07
  • 2
    @DWuest `this` keyword is optional, since the local variables are named differently. – CoolBots Feb 09 '19 at 23:07
  • You need it to initializes the instance variables that you're initializing. What you don't need is code in the default constructor that initialises them to their default values: `age = 0;`. – user207421 Feb 09 '19 at 23:12
  • Your example is a good one. If you hadn't added the constructor with parameters none "MyCats" would ever have a name and all of them had an age "0". Thanks to that parameterized constructor your Cats can have actual names instead of staying nameless! For me thats reason enough! (sure: different ways to accomplish this - you found one), – kai Feb 09 '19 at 23:48

1 Answers1

6

That's for easily creating your class without needing extra code. For example, instead of doing:

MyCats a = new MyCats();
a.setAge(12);
a.setName("Foo");

You can just do:

MyCats a = new MyCats(12, "Foo");

Simpler, hum?

Other reasons you might prefer the later, if shortness is not enough:

  • You can initialize all calculated fields that depend on several fields inside the constructor, using the values provided.
  • You can validate input and thrown exceptions in case of invalid arguments, even for checks that requires multiple arguments for that.
  • You must do that if your fields are final and your class immutable, in which case there is no setters available.

Mostly in the last case, it's very useful to be able to check for correctness upon construction and disallow any objects from being in a invalid state, saving lots of errors later on.

Luan Nico
  • 5,376
  • 2
  • 30
  • 60