0

I am currently confused and I don't know when exactly should I call the get-method. What is the difference when I call my variable without get and if I call it with get. I know what "this" does but I am not really sure if there is a difference between calling the method and calling the variable. for example :

    public class Student() {
    private int idNumber; 
    private String name;
    Student (int idNumber, String name) {
       this.idNumber = idNumber; 
       this.name = name;
      }
      public int getIdNumber() {
       return idNumber;
        }
      public String getName() {
        return name;
       }
      // method to add 2 idNumbers
       public int addNumbers(int no) {
       int result = this.idNumber + no; 
      int result = this.getIdNumber() + no; 
       }

Is there a difference if I called the get method and not the variable itself in this case? Thank you very much in advance.`

O.AEESS
  • 9
  • 3
  • 1
    `this.variable` refers to field in current object. `this.getVariable()` is a function call. – mallaudin Nov 21 '16 at 19:06
  • 1
    @bradimus I don't think that this is a duplicate. The referenced question asks about getters and setters for the _outer_ world. This question instead asks about using a getter (or not) _inside_ the same class. – Seelenvirtuose Nov 21 '16 at 19:13
  • The question is a duplicate. There is no mention in the referenced question that it should be only applied to "the outside world". Same rules apply for both situations. – Martijn Burger Nov 21 '16 at 19:27
  • The dupe has a lot of things that might be more related to encapsulation and "the outside world", but there's plenty of reasons included that would affect internal access as well. Besides, it's a good read for the OP anyway. – Kayaman Nov 21 '16 at 19:36

5 Answers5

0

Is there a difference if I called the get method and not the variable itself in this case ?

There is NO difference, but, the code will be more readable if you directly access the variable using this.idNumber rather than accessing the variable using the method this.getIdNumber(). If the code is readable (which is important), then you can understand it better and maintain it easily.

Vasu
  • 21,832
  • 11
  • 51
  • 67
0

this.variable is a direct reference to the variable itself. this.getVariable() is a method, and while it might just give you this.variable as a result, it might do anything else. It's just a variable.

This has some uses. I like to program defensively when it comes to getters.

For example, imagine we have the following class structure.

public class School {
    private final Set<Person> teachers = new HashSet<>();

    public boolean addTeacher(Person teacher) {
        return teachers.add(teacher);
    }
}

Now, we want the functionality to return the set of teachers in the school. It might be tempting to do this...

public Set<Person> getTeachers() {
    return this.teachers;
}

... but this can have some unintended consequences. For example, if one client of your class does this...

Set<Persons> persons = someSchool.getPersons();
persons.clear();

... then suddenly your internal persons set has been emptied! This might be unintended behavior to expose to your class' clients (I've had a few IRL professional cases where this has happened!). The answer is to not give your users access to your internal, private object, by implementing getTeachers() in a slightly different manner...

public Set<Person> getTeachers() {
    return new HashSet<Person>(this.teachers);
}

Now, the getTeachers method will return a brand new Set of Persons. No matter what the user does to the result of getTeachers, the private collection (this.teachers) cannot be modified by acting on the set. This gives the School class more control over its internal state, and is one good example of when a "getter" doesn't return the actual variable that it's "getting".

nasukkin
  • 2,460
  • 1
  • 12
  • 19
0

What is the difference when I call my variable without get and if I call it with get...

Generally, if you are talking about accessing the attribute within the class, there is almost no difference because you are still accessing the same attribute.

However there is still a subtle difference which I will get back to that point later.

Now, if you are accessing the attribute from outside the class. You won't be able to access the attribute if it is marked with private access modifier.

Example:

class Hero{
    private int health;     //inaccessible from anywhere outside the class

    public int getHealth(){
        return health;      //allows access of health outside the class
    }
}

Now imagine if health was declared as public and you just access it directly using myHero.health and one day you realize that you need to change the data type of health to something else such as a class to represent health:

class Health{
    private int minHealth;
    private int maxHealth;
    private int healthValue;
}

But you have already been coding with myHero.health so frequently that you are having trouble to change your code now.

Now, imagine if you have been coding with myHero.getHealth(). It will make a difference now, because all the code can continue to use the getter which is getHealth() to get the health value. All you need to do is to change the implementation of getHealth() to return the health value:

class Hero{
    private Health health;     //Data type changed, no worries..

    public int getHealth(){
        return health.getHealthValue();  //Implementation can be changed here..         
    }
}

Data type of health can be changed without much worries (in terms of other modules which is dependent on it directly). Since it is private, there is no dependency on it and we can change it without having too many side effects.


Now going back to talk about accessing the attribute within the class itself. Personally I believe it will still be safe to call the getter rather than accessing directly on the attribute.

Using the following example:

class Circle{
    private double radius;
    private double area;

    public double getArea(){
        return Math.PI * radius * radius;
    }
}

This is not a good design, but for explanation sake, I have written it this way.

So in the class Circle itself, it may seems that this.area and this.getArea() does the same thing. But in certain occasions, the getter itself may be doing a job more than just merely passing you the naked variable. Writing this.area may have the tendency to give you 0.0 instead of the area based on the radius.

Once again, not the best example, but you get my point..

user3437460
  • 17,253
  • 15
  • 58
  • 106
0

For a new class MyClassA and there fields, the best practice is : - add private fields - add public getters and setters for each field that set values and get values in and from fields

In this case, when you instantiate a new MyClassB for example which contains an instance off MyClassA, your myClassB object can only uses getters and setters and can't interacts direcly with MyClassA fields.

The advange is for example the possibility to check value before to store it in myClassA.

In your example, if you want idNumber can't be negative, use this setter:

public void setIdNumber(int newValue) {
    if(newValue<0) {
        this.idNumber=newValue*-1;
    } else {
        this.idNumber=newValue;
    }
}

The other advantage to uses setters and getters is you can lock field to be read or write from external Object. You have just to only write the code of the getter to allow read or setter to allow write.

And the last important point to use private field with getters/setters is that all libraries that use reflexion to dynamicaly read/write in an unknow object use these getters/setters. With reflexion you can get the list of fields of any object (private or public) and the for read/write on it, you juste have to call "getMyField"/"setMyField" for a field named "myField" (add get/set and upper the first letter)

The best example I know is the serialization ! It allow you to convert any object in a sequence of bytes in order to store it in a database or a file. And then you can read this sequence and deserialize to get again your object in the same state of the origin. And of that with only 1 instruction :)

Elloco
  • 235
  • 2
  • 9
  • "All libraries that use reflectionion to dynamicaly read/write in an unknow object use these getters/setters." That's not true. Getters/setters are not needed for reflection, and a lot of libraries don't need them or can be configured for field access etc. Also serialization is not related at all to getters and setters, it's a completely different mechanism and can access all data with no problem. – Kayaman Nov 21 '16 at 19:49
  • Thanks Kayaman for the clarification... so all my explanation is bad :p (sorry) – Elloco Nov 23 '16 at 09:30
-1

The member variables of the class are private, so they can't be used outside of the class. To the outside world, you need to use getVariable(), but inside the class, in member methods, you can reference the variable directly.

This is what is known as "encapsulation", and is one of the fundamental parts of object oriented programming (along with polymorphism and inheritance)

Kevin Milner
  • 821
  • 2
  • 14
  • 30