Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Static Methods and Fields take up memory in an instance of the class they are defined in?

For example if I were to create the following class:

public Class ExampleClass {
  
  private static String field1;
  private String field2;

  public ExampleClass(String field2) {
    this.field2 = field2;
  }

  public static staticMethodExample(String field1) {
    this.field1 = field1;
  }
}

If I were to create an instance of ExampleClass. Would that instance contain the code for the static method and/or field I created?

I have an object that will represent some data from a row in my database. I would like to create the a list of these objects from every row in the database. The database has thousands of rows. The static methods I am creating will format the values from the database before putting them into the objects constructor.

I don't want to bloat the code by having the method stored in every instance of the object. So if static methods do take up space in every instance of an object, then I would much rather create a separate class of of a name like ExampleClassBuilder. And put the formatting static methods in there.

like image 470
Matthew Cole Anderson Avatar asked Oct 30 '20 15:10

Matthew Cole Anderson


Video Answer


1 Answers

No, static methods and fields do not take space in an instance of the class.

You are making a number of confusions here. When you compile your program, the code of each of your method (static or not) is "stored" in your compiled program (in the case of Java, in .class files). When you execute a program, static members - that "belong" to a class, like field1 in your question - are allocated once for your whole program. The other "normal" class members - like field2 in your question - are allocated for each new instance you create.

When you create a new instance of an object, the code of its various methods is not "allocated", as it already exists in compiled form in your program.

like image 123
Patrick Avatar answered Oct 03 '22 23:10

Patrick