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:
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:
Person
, a pointer to its superclass etc. getName()
and any other methods For each instance of Person
, we get in the heap:
age
String
object name
So, at least conceptually, you could see the runtime handling a call to aPerson.getName()
as:
getName()
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.