Christoph S.
Christoph S.

Reputation: 603

Does it make sense to declare all methods as static to save memory?

(When) does it make sense to declare methods static in this way? Will it save memory? How about the performance?

If I am right, toString() in the Integer wrapper class is working like this.

class Address {
  private static void method(Address adr) {
    // do something
  }

  public void method() {
    Address.method(this);
  }
}
class OtherClass {
  public static void main(String[] params) {
    Address a = new Address();
    a.method();
  }
}

Upvotes: 0

Views: 68

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24681

All instances of a class share the same code for each method. It doesn't matter whether the method is static or not - as long as the class is loaded at all, memory is being taken to define the contents of the method.

This isn't duplicated on a per-instance basis. Why should it be? All that changes between instances is attributes, not behaviors. Adding more instances will consume more memory, yes, but only for holding attributes - the behaviors still need only be defined once.

Upvotes: 2

Related Questions