Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDanna Lidia
5,933 PointsConstructor and setters
By creating a constructor, are we not setting values? If so, is it necessary the setters methods?
1 Answer
syed ehteshamuddin
969 PointsThe benefit of using constructors is you can initialize the object when creating the object for ex
ClassA obj = new ClassA("hello"); // creating and initializing the object using the constructor which takes one string agrument
So why use setters you may ask ?
ClassA obj = new ClassA(); // created an object using default constructor
i want to set text "hello" to the object , how do i do that ?
obj.set("Hello") // if the class ClassA has a setter method which accepts string args i can do that
the other reason why we need setter is to prevent other objects accessing fields directly instead we expose them via getter and setter methods for ex
ClassA {
private int score;
public int getScore(){ return score; }
public void setScore(int arg){ score = arg; }
because we marked score field to be a private other objects outside this class can't access this variable the only way to access this variable is through set/get methods.