When I have a class like this:
class Test {
private int _id = 0 ; // 4 bytes
private int _age = 0 ; // 4 bytes
}
I’m sure that each instance of it will consume more than 8 bytes in memory because of the 2 integers.
But what about methods? If I have a class with a million methods, and 2 instances of it, are the methods going to take twice as much place in memory ?
How does it work?
Thank you.
No. Methods occur only once in memory1. They don’t vary on a per instance basis, so they don’t need storage on a per-instance basis.
An object in Java basically consists of some fixed-size “housekeeping” (a pointer to the type information including the vtable), potentially GC-related bits (think mark and sweep), information about the monitor for the instance etc – and then the fields.
1 This is a bit of a simplification. There may be various representations, such as bytecode, native code etc – but that’s regardless of separate instances.