4

In C++ virtual member functions are part of the class and make the object bigger as the object has to keep a pointer to its functions (base or overriden). If I'm in Java and I want to make an object with the smallest size, will making the methods final prevent the class from holding pointers to the methods and overall reduce the size of my objects of this class? Is it also true for private methods?

class Small {
    float x;

    final float getX() {
        return x;
    }

    final void setX(float x) {
        this.x = x;
    }
}
Winter
  • 3,894
  • 7
  • 24
  • 56
  • 4
    No. Final in Java just means nobody can override the method. The class will be the same size with or without this keyword. – Hitobat Nov 10 '18 at 11:45
  • 3
    C++ can save the vtable pointer if an object has no virtual functions. One could think that something similar might be possible in Java for classes which have only final methods. But: since all classes in Java extend from `java.lang.Object` and `java.lang.Object` has non-final methods there can't be a class with only final methods. – Thomas Kläger Nov 10 '18 at 12:45
  • @ThomasKläger usually, the reflective type information and the vtable share the reserved space within a Java object, so even without overridable methods, the presence of the (`final`) method `Object.getClass()` or the `instanceof` operator require the presence of that per-object overhead. – Holger Jan 09 '19 at 11:41

0 Answers0