0

(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();
  }
}
Christoph S.
  • 585
  • 3
  • 16

1 Answers1

2

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.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • My understanding was that methods which are not static, will be copied in every instance of a class. So, in Java it is not true? But why the `toString()` method (e.g. in class `Integer`) is working like this? – Christoph S. Oct 16 '21 at 16:16
  • They're not copied, no. They don't have to be copied to be *run* separately on different objects, however. The amount of memory consumed by a Java object has no relationship at all to what methods are defined on it, static or not. – Louis Wasserman Oct 16 '21 at 16:32