Suppose you have a class Delta that implements interface Alpha. Alpha has methods a, b, and c, and Delta defines an additional method d. If the line "Alpha object = new Delta()" is written, will the compiler allocate memory for the method d even though the reference will not be able to access it?
CodePudding user response:
will the compiler allocate memory for the method d even though the reference will not be able to access it?
No, but this has nothing to do with the reference. The compiler does not allocate memory for methods for each object, period. Objects on the heap consume a constant amount of memory plus the memory for their fields. You can see more details e.g. here: https://github.com/openjdk/jol.
Each method is loaded into memory once for the entire class; each individual object (e.g. new Delta()
) does not load the method again.
CodePudding user response:
Yes, the memory will be allocated for the method 'd'. It won't be 'visible' if you try to access it via Alpha reference without casting. But because you are creating an object of type Delta the method 'd' is there.