简体   繁体   中英

In Java where do the static methods go during the creation of an object in java?

If there is a class with some methods, whenever we create a new object then that object gets created on the heap with the fields and methods. If we have a class with static and normal methods and we create an object of this class, the instance variables and normal methods still exist but how are the static methods created ?

All methods, both static and non-static, are part of the class , and classes are stored in non-heap memory.

All that resides in the heap is a structure containing:

  • a pointer to the class of which this object is an instance
  • The current values for each non-static field (references for object fields, values for primitive fields)

So for example:

 public class Person {
     private String name;
     private int age;

     public String getName() {
         return name;
     }

     // ... etc.
 }

One structure in non-heap memory contains:

  • Metadata about the class eg its name Person , a pointer to its superclass etc.
  • The bytecode for getName() and any other methods
  • JIT optimised versions of the bytecode

For each instance of Person , we get in the heap:

  • A reference to the class entry
  • An int value for age
  • A reference to a String object name

So, at least conceptually, you could see the runtime handling a call to aPerson.getName() as:

  • Look at the object's record in heap
  • Follow the reference to its class
  • In the class, find the method getName()
  • Run the method, using the object's record in the heap for fields

This means that if you have 1000 instances of Person , you still only have one copy of the code from the class, which is perfect because it does not change from one instance to the next.

If Doctor , Nurse , Patient are all subclasses of Person , and if none of them override getName() , then the code for getName() still only exists once in memory. (Conceptually) when you call aNurse.getName() the runtime will look in Nurse for getName() , if found, run that, otherwise look in the superclass Person , find it, and run that.


I've said "conceptually" a couple of times. In reality some of what I've described as happening dynamically may happen statically at compile time. This doesn't really matter as far as understanding the effect on memory and performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM