If we use constructors do we need to use setters and getters. I am totally confused between these terms could someone please elaborate.
If we use constructors do we need to use setters and getters
First of all you cannot have a class without a constructor, when you do not provide any compiler will generate them for you. You should not use setters and getters unrelated if you define your own constructor or not. When you design a class you design it's interface and then add member variables to implement that behavior and those members are internal representation of the class and outside world should not be aware of them - that is what data encapsulation is for and that's why we make them private or protected. When you add members first and then blindly provide getters and/or setters - that is a wrong approach to OOD.
Use constructors to create objects. Use getters to get information from an already existing object. Use setters to change an already existing object.
Any particular class may will need one or more of these things but not every class will need all of them. In particular immutable classes can't be modifed after they've been created so don't need setters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With