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..