That answer is incorrect.
Adding implemented interfaces or methods does not influence the memory required for individual instances of a class.
First of all, conceptually it doesn't make sense.
Implemented interfaces and methods are per-class information. Two instances of the same class will always implement exactly the same interfaces and have the exact same methods. As such, it makes no sense for the JVM to store that information per-object.
Second, you can easily verify that with sample code like this:
public class MyClass implements Comparable<MyClass> {
private final long l;
MyClass(long l) {this.l = l;}
@Override
public int compareTo(MyClass o) {
return 0;
}
public static void main(String[] args) {
long l = 0;
try {
var list = new ArrayList<MyClass>();
while (true) {
list.add(new MyClass(l++));
}
} catch (OutOfMemoryError e) {
System.out.println("Created " + l + " objects before things went south ...");
}
}
}
Running this with -Xmx32m
using Java 11 will create about 200000 objects on each run for me (with slight variations, probably due to GC details).
Removing the Comparable
interface and/or the compareTo
method does not significantly change that value.
You can try adding additional fields or removing l
, which will change the number.