0

So when you make an instance of a class such as:

class Example {

     public static void main(String[] args) {
          Example example = new Example();

     }

}

Will anymore resources be used if I did:

class Item {

     public Item() {
          //empty
     }

}


class Example extends Item {

     public static void main(String[] args) {
          Example example = new Example();

     }

}

If so, why?

Vince
  • 14,470
  • 7
  • 39
  • 84
  • 3
    You need X more memory to store the `.class` file for `Item`. You really shouldn't worry about that. – Sotirios Delimanolis Mar 17 '14 at 02:14
  • For each base class or interface `Example` uses, I would expect each instance of `Example` to be 4 bytes larger. Not significant at all unless you make zillions, like if you use an object to represent something tiny like a node on a graph. – VoidStar Mar 17 '14 at 02:24
  • So it won't take much memory? Lets say I had one method in `Item`. 100 different classes extending `Item` wouldn't take much more memory than 100 different classes putting that method in individually. (all methods would be overriden if extended) – Vince Mar 17 '14 at 02:25

1 Answers1

1

There is an insignificant increase in memory usage due to the fact that you have an extra class to load. If you have 100 subclasses of Item, you would have 100 extra classes to load ... and if you take it far enough the extra memory usage for the extra code will be significant.

However, an instance of Example will occupy the same space as an instance of Item because Example does not declare any instance fields. Note that extra methods or method overloads do not contribute to the size of an instance.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • So when you have an instance of `Example`, a space in memory the same size as `Example` will be used for `Item`? (if `Example` had no original methods) – Vince Mar 17 '14 at 02:40
  • That is correct. And it won't make any difference if there are extra methods in `Example`. Methods do not occupy any memory in an instance. They only use memory at the class level ... and that is a once-off thing, so it is probably going to be insignificant. – Stephen C Mar 17 '14 at 02:41