Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason for static methods?

Tags:

java

I can't really seem to understand static methods. I read many articles on it and also have looked at it in textbooks and the Java docs. I know that you can use static methods to access static variables. Is there really any other reason for class methods other than to get a static variable? If there is another reason can I sort of maybe get an explanation of why? I made this thread also because I haven't found anything in SOF about this.

Here is an example code:

public class Bicycle {

    private int cadence;
    private int gear;
    private int speed;

    private int id;

    private static int numberOfBicycles = 0;


    public Bicycle(int startCadence,
                   int startSpeed,
                   int startGear){
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;

        id = ++numberOfBicycles;
    }

    public int getID() {
        return id;
    }

    public static int getNumberOfBicycles() {
        return numberOfBicycles;
    }

    public int getCadence(){
        return cadence;
    }

    public void setCadence(int newValue){
        cadence = newValue;
    }

    public int getGear(){
    return gear;
    }

    public void setGear(int newValue){
        gear = newValue;
    }

    public int getSpeed(){
        return speed;
    }

    public void applyBrake(int decrement){
        speed -= decrement;
    }

    public void speedUp(int increment){
        speed += increment;
    }
}
like image 849
user2522055 Avatar asked Dec 29 '25 16:12

user2522055


2 Answers

Instance methods can access class variables as well.

A good example is a utility class: what do you do when you need a quick thing done, but creating an object would be cumbersome? That's right: static methods.

public static class Utils {
 public static void DoSomething(SomeClass x) { }
}

That way we can just call Utils.DoSomething(myObject);

instead of

Utils util = new Utils();
util.DoSomething(myObject);

Or, in your example, it keeps a count of how many bicycles are created in total. By saving it on class level, it will keep the state of the variable synced across all objects.

like image 92
Jeroen Vannevel Avatar answered Dec 31 '25 04:12

Jeroen Vannevel


By class you mean static I assume? You can use static methods for utility classes. It keeps you from having to instantiate a class to access a method. For instance, I can write method that counts the number of letters in a String called getNumOfLetters and call it by using StringUtil.getNumOfLetters assuming String utils is the name of the class.

like image 38
Skylion Avatar answered Dec 31 '25 04:12

Skylion