user2522055
user2522055

Reputation: 159

Is there a reason for static methods?

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;
    }
}

Upvotes: 3

Views: 305

Answers (5)

frnhr
frnhr

Reputation: 12903

Usually books tell you something like "class is like a blueprint for objects". But I like to think about classes as "factories" for objects. (not to be confused with "factory pattern", though there are similarities!)

With this example, you can think about your class as a "factory of bicycles". You might wanna do a stopProducingBicycles(), or getTotalBicyclesCount(). Or something a bit more fancy: setNewBicycleColor(red).

Following the thought on setNewBicycleColor() - there is nothing that prevents you from accessing class static properties in the constructor, e.g. "color", so that all new bicycles have default color "red".

You might wish to keep a reference of each new bicycle in your class (that would be a static property). Then at some point you might do Bicycle.AllInstanciesSelfDestruct() :)

Upvotes: 2

Mike Strobel
Mike Strobel

Reputation: 25623

Is there really any other reason for class methods other than to get a class variable?

Assuming by "class methods" you are referring to static methods, there are any number of uses for them. Apart from exposing global constants or shared data, they are probably most commonly used for utility functions which do not need to be performed within the context of an object instance.

For example:

  1. Collection-related operations like sorting, reversing, etc. (see: java.util.Collections)

  2. Fixed math functions (see: java.lang.Math)

  3. Wrappers for other operations that have with well-defined behavior for null arguments (see: java.util.Objects::equals() as opposed to java.lang.Object::equals())

Factory methods are another popular use case. Factory methods perform similar duties to constructors, but allow for some added flexibility:

  1. They may have more descriptive names, perhaps communicating the intended purpose of the object(s) being constructed.

  2. They can return a base type and decide which concrete type to instantiate based on internal logic and/or options/hints passed as parameters.

  3. Factory methods for many concrete types can be grouped together in one location, improving discoverability. For an example, see java.util.concurrent.Executors.

Upvotes: 2

Paul Samsotha
Paul Samsotha

Reputation: 208944

Methods aren't just for accessing a class's data but also manipulating data

Upvotes: 1

Skylion
Skylion

Reputation: 2752

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.

Upvotes: 3

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

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.

Upvotes: 5

Related Questions