0

Why use constructors

Why use a constructor when you could just assign the variable a value when you initialize it?

25th Jul 2017, 6:22 PM
Paul Silvestri
Paul Silvestri - avatar
2 Antworten
+ 5
Assigning the variable can be a default value. But that's something ALL instances of the class will have. With a constructor, you can change the values to be different for every object. Here's an example Lets say I have the constructor: int age; String name; Person(int age, String name){ this.age = age; this.name = name; doStuff(); } private void doStuff(){} If I wrote this instead: String name = "bob"; int age = 24; Every object instance is going to have that age and name. So, I'd have to change it with a setter. Meanwhile, I could have just changed it with the constructor instead.. Constructor: Person bob = new Person(19, "Bob"); Person joe = new Person(88, "Joe"); Person lia = new Person(22, "Lia"); Person george = new Person(28, "George"); No Contructor: Person joe = new Person(); /* keep in mind, this actually still uses the default contructor */ joe.setName("Joe"); joe.setAge(88); joe.doStuff(); See how redundant / tedious that is? For one person! Plus, the doStuff() method is now forced to be public. Far easier with contructors.
25th Jul 2017, 7:05 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
when you initiate and give initial values as you say, you're using a constructor. If you don't give initial values, guess what. Yep, you're using a constructor. That's what constructors are for, if you don't create them, java uses default constructors.
25th Jul 2017, 6:38 PM
voidneo