-3

Let's say I have this code:

class A {
  void f(){
    // ... some long function code
  }
}
for (int i = 0; i < 1000000; i++) {
  A a = new A();
}

My question is: will the function if be replicated a million times in memory in this case? If so, does it make sense to use static methods?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Moshe Shaham
  • 15,448
  • 22
  • 74
  • 114

2 Answers2

4

Why do you think the method f() needs to be replicated million times? The method is nothing but a set of reusable instructions group in a single namespace. The definition of method will get it from the Byte code at the run time easily. So, JVM does not need to copy the definition of method in each and every Object created as it does not need to do so and it is true for each type of method static, nonstatic.

Amit Bera
  • 7,075
  • 1
  • 19
  • 42
0

It always depends.

Sometimes method relies on properties of a object, so on every object such method would behave differently.

On the other hand, static method must be independent of object non-static properties, so it can be called without instantiating object.

It depends what you want to achieve.

Example: let's say you have a class User and you'd like to get age of object of that class. Would it make sense to have common static method? No, as every user would have different age.

On the other hand, you'd like to have method to get the type of person, something like "I am user" - this would be independent from the state (properties) of an object, so you could make this method static.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69