+ 1
Why we use g1.getColor(String c) instead of using g1.color directly?
4 Answers
+ 3
The getter method doesnt accept any arguments conventionally. We use getter methods with that syntax because it makes the code more readable and is a convention, although you are free to use any name you want for the method.
Naming a method color() will be confusing as we don't get any info wether the method is a getter or setter semantically getColor() and setColor() are the norm. :)
+ 2
good question. we could use it either way but the first way is preferred for having better control and security for data access and modification.
The standard is to declare all variables in a class as private so anyone can't access them directly. The user is allowed to modify the data in a limited way only.
example 1: suppose you want a variable to have only values >5
if you let user say obj.var=2 you lose
so you limit access and user now says objsetvar(2);
and inside this function you have already put a check
if(val>5)
var=Val
so you can rest assured undesired behavior won't happen
example 2: ATM machine. why not leave the ATM open and let people take out their money directly instead of a procedure? you know how people are going to abuse the freedom of access!!!!!!
+ 1
Wew! Thanks people.