0

I am using getters and setters to for the purpose of encapsulation.

public class Student {

    private String studentID;
    private String studentName;
    private String address;

    public Student(){
        //default constructor
    }

    public Student(String studentID, String studentName, String address) {
        super();
        this.studentID = studentID;
        this.studentName = studentName;
        this.address = address;
    }

    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

the variables studentID, studentName and address are declared as private, with the intention of encapsulation.

but we could also do the same task by making the variable accessibility level from private to public, is it really helps to apply encapsulation by the use of setters and getters?

only I can understand the use of getter and setter is users of the class dows not need to have an idea about the names of the variables used in the class as setters and getters makes sense to the users of the class

ex- objectofStudentClass.setStudentID("S0001");

Is there any difference between main difference between making getters and setters instead if making the variable access level to public.

Question 2: also here I have made parameterized constructor matching to the variables/fields in the class Student. is that throw away the concept of encapsulation?

Roovi D
  • 13
  • 3
  • @gnat but that does not describe parametarized constructor my 2nd Question – Roovi D Oct 06 '15 at 08:03
  • [How to handle a question that asks many things](http://meta.stackoverflow.com/a/267059/839601) – gnat Oct 06 '15 at 08:07
  • @gnat could you please help me to resolve this problem? – Roovi D Oct 06 '15 at 08:13
  • @RooviD: What is the actual problem you are trying to solve? – Robert Harvey Oct 06 '15 at 08:27
  • @RobertHarvey I want to understand the concept of Encapsulation in the code which I have mentioned above. – Roovi D Oct 06 '15 at 09:08
  • see also [What is a constructor? And what are set/get methods in Java?](http://programmers.stackexchange.com/questions/140776/what-is-a-constructor-and-what-are-set-get-methods-in-java) (looks like every year students get the same questions and dump them over here) – gnat Oct 06 '15 at 09:15
  • You wouldn't see the real benefit in using methods which retrieve or change the inner components of your class for your specific example, because your class is anemic, stupid, does nothing... It's an example of a bad Model. Add some logic to processes when changing member variables of said class and you will see exactly what is the point of having private variables rather than exposing them directly. – Andy Oct 06 '15 at 11:47

2 Answers2

1

Yes, there is a huge difference.

Having getters and setters allows you to change their implementation (for instance, to add range checking, audit logging, statistics updates etc.) in the future without having to change all client code. Having a public variable would make such maintenance a breaking change. Very often this is the difference between a change being feasible and being too invasive/risky to perform.

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310
  • Could you please tell me what is the meaning of parametarized constructor my 2nd Question? – Roovi D Oct 06 '15 at 08:09
  • @RooviD: A parameterized constructor is one that takes parameters. You might want to ask yourself, "What does the encapsulation accomplish?" If you're just setting the underlying fields, the only thing you accomplish is that adding validation later isn't a breaking change. That's no small thing, however. My suggestion is that you pick up a good book and learn Java on its own terms. Encapsulation is just one small (but important) feature of programming. – Robert Harvey Oct 06 '15 at 08:29
  • Oh, and parameterized constructors are a feature of immutable objects. – Robert Harvey Oct 06 '15 at 08:34
  • @RobertHarvey it seems we can use setter methods to set values to fields dynamically , and use the constructor to initialize the fields when object is creating – Roovi D Oct 06 '15 at 09:52
  • @RooviD Constructor makes sure that your object is created in a proper way. That's its purpose. You don't need to include all parameters to be set to internal variables of your object if some are not required, but you need to set all those that are. Without required fields, your object would be in an invalid state, a state, you don't want. – Andy Oct 06 '15 at 11:52
1

The first thing to note is that public getters and setters do not provide encapsulation:

[…] getters and setters do not achieve encapsulation or information hiding: they are a language-legitimized way to violate them.

James O. Coplien & Gertrud Bjørnvig. Lean Architecture. Wiley. 2010. p. 134.

So the answer to your question as to whether there's a difference between them and just having a public field is: there is no difference as far as encapsulation is concerned.

What they do provide though is support for the Open-closed principle. You can later change the behaviour of the getter and setter, to add a guard cause for example, without changing the API. This though leads down another potentially bad path, as any getter/setter that doesn't just get/set a field risks breaking the POLA principle.

You final question leads you to the "correct" way to use getters: use a constructor to set the fields and only provide getters. That provides true encapsulation and enables your fields to be invariant, which improves thread-safety.

David Arno
  • 38,972
  • 9
  • 88
  • 121
  • do you mean that setters break the encapsulation? – Roovi D Oct 06 '15 at 09:45
  • No, setters break the invariance of the fields. – David Arno Oct 06 '15 at 09:46
  • how does it relate to encapsulation? – Roovi D Oct 06 '15 at 09:47
  • @RooviD, a getter and setter that simply get/set a field offer no encapsulation. A setter that provides a guard (eg verifies the value being set) provides encapsulation, but risks breaking the principle of least astonishment. Using a constructor to set fields and getters (with no setters) provides encapsulation to achieve invariance. – David Arno Oct 06 '15 at 10:05
  • @RooviD Avoid getters and setters unless you have really good reason to use them. Objects should define behaviour (the object does something specific to it). If you have an object that just allows you to go in and manipulate its internal state without any context then you clearly don't know what its behaviour is and this is bad design. For example, why is anything other than Student manipulating the Student objects internal variables. Student should be doing that based on requests made to it, not some external object that has to know about students internal state. "Don't ask, tell" as they say – Cormac Mulhall Oct 07 '15 at 15:02
  • @RooviD Avoid object that are just dump data containers, that is not object oriented design. The first question is not what data does the object have, but what behaviour does it have. Define that first, then worry about state – Cormac Mulhall Oct 07 '15 at 15:04