View Single Post
Old 08-02-2012, 07:47 PM   PM User | #13
tomjas
New to the CF scene

 
Join Date: Jul 2012
Posts: 7
Thanks: 1
Thanked 0 Times in 0 Posts
tomjas is an unknown quantity at this point
Quote:
Originally Posted by Fou-Lu View Post
No that's not right. The setters and getters should be public if the property can be accessed from outside of this class. You don't need to specify multiple write methods for a single property, just the one is sufficient. If you make everything private or protected, than this class becomes useless outside of itself since you cannot call anything on the object outside of it.
Ok - there have been some misunderstanding. In my first post I tried to give as simple snippet of code as possible and the whole discussion went wrong way. My mistake was giving something like that:
Code:
class Num {
    public int num() {
        i = 10;
        return i;
    }
}
and we started to discuss that variable "i" should be private/protected to avoid changing it so it must be returned and so on. I am learning from http://docs.oracle.com/javase/tutorial/java/ and I found such example:
Code:
public class Bicycle{
        
    private int cadence;
    private int gear;
    private int speed;
    private int id;
    private static int numberOfBicycles = 0;
        
    public MouintainBicycle(int startCadence, int startSpeed, int startGear){
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;

        // increment number of Bicycles
        // and assign ID number
        id = ++numberOfBicycles;
    }

    // new method to return the ID instance variable
    public int getID() {
        return id;
    }
        ...
}
And again - method MountainBicycle must be public so as to we could invoke it and pass parameters. Right? The last statement of this method is "id = ++numberOfBicycles;" After invoking it from my main method (and of course writing for this method some stupid code that calculates somehow id) I can still obtain the id like this:
Code:
...
Bicycle bke = new Bicycle();
bike.MountainBicycle(10,10,10);
int numberOfBicycles = bike.id;
So again - what for is the getID() method with its "return id" statement? There is no need to return it if we have access from outside to calculated id? That's what I was asking from the beginning. Of course I assume that there are some other reasons for that than just "good programming practices".
tomjas is offline   Reply With Quote