Imagine this extreme situation:
A class City
with 10 variables, but 1000 lines of functions and logic that operates these variables.
Class Person {
// 10 variables
int age = 20;
int height = 180;
String name = "Name";
.
.
.
// 1000 lines of functions and logic
public void increaseAge(int years){
age =years;
}
public void doLogic(){
//some logic
}
.
.
.
}
I don't know exactly how much memory will occupy a instance of this class, but let's say that the variables occupy 10 bytes
and the 1000 lines of functions occupy 1 kb
to put a sample amount.
If you have 100 instances of that class, the 100 times repeated variables should occupy 10*100 bytes
but what happens with the functions? will you have 1*100 kb
memory occupied for these functions? Or will the compiler do something to avoid that?
Thank you.
CodePudding user response:
I don't know exactly how much memory will occupy a instance of this class, but let's say that the variables occupy 10 bytes and the 1000 lines of functions occupy 1 kb to put a sample amount.
An instance of this class will occupy 10 bytes in this scenario. (That's not actually possible, as objects have headers of various fixed sizes ranging from 4 to 12 bytes depending on JVM settings, and even then they're rounded up to a multiple of 8 bytes, but the point is that you only pay for the variables of the class.)
There is only one copy of the implementations of the functions for a given class stored in memory.