Search code examples
javagetter-setter

Why do I need to use a setter - instead of a getter - to set data?


Suppose I have a class which has as one of its fields an object, SampleData, and a getter and setter for the field.

public class someClass
{
    private SampleData sampleData;

    public SampleData getSampleData()
    {
         return sampleData;
    }

    public void setSampleData( SampleData sampleData )
    {
        this.sampleData = sampleData;
    }
} 

Say I've instantiated someClass. And suppose I have another SampleData already available. So with the setter I would do the following,

someClassInstantiated.setSampleData( anotherSampleData ); 

Why do I need to use the setter, setSampleData to set the value of this field? Why can't I do something like this instead?

SampleData sampleData = someClassInstantiated.getSampleData();
sampleData = anotherSampleData;

Solution

  • People seem to forget that Java still uses memory pointers to reference data, it just hides all the awesome pointer arithmetic that C/C++ has ;)

    So, basically, when you do this SampleData sampleData = someClassInstantiated.getSampleData();, sampleData is pointing to the same memory location as someClassInstantiated.sampleData, for example...

    Initial State

    How ever, when you do sampleData = anotherSampleData;, you change the memory location that sampleData is pointing to be the same as anotherSampleData, this doesn't affect what someClassInstantiated.sampleData is pointing, it remains unchanged

    Updated State

    So if I point to a location that contains data, then why null? If I print both the sampleData and anotherSampleData after using the getter method, sampleData is null and anotherSampleData is not null, but from what you are saying they are pointing to the same location

    This is because someClassInstantiated.sampleData still points to null - this is the default value assigned to it when it was instantiated and (based on your example) has not been changed.

    In the long run, you really, really don't want it to work the way you're trying to use it, as it breaks the principle of encapsulation, where the object is responsible for the management of the data.