I have begun learning OOP in Java, and see no need for constructors. Can't we just assign the values to the variables directly. So what's the need for constructors? What's the difference?
Asked
Active
Viewed 55 times
0
-
The difference is encapsulation. With a constructor, the class can hide its private representation. Encapsulation allows the class to ensure its own invariants, and to change its representation over time. – Andy Thomas Aug 19 '15 at 16:06
-
You have to copy initialization code for each object. Think that you changed those initializer code. Then you have to change for each object. Instead use class' constructor. Plus, encapsulation is another motive, as Andy said. – Ali Yeşilkanat Aug 19 '15 at 17:23