简体   繁体   中英

Amount of Memory allocation for Creating Object based on Class Size

How does the computer know how much memory to allocate for an object (based on different sizes of classes)? An example is below.

public class Point(){
   public int x;
   public int y;
   public Point(int x, int y){
      this.x = x;
      this.y = y;
   }
}

Point x = new Point();

With the "new" keyword allocating memory for a new object first and then calling the constructor of the class, how does the computer know before calling the constructor how much memory to allocate for the newly created object?

The JVM knows because it has read the .class file describing the class.

If you run the command javap -v Point.class , you can see for yourself:

...
class Point
  minor version: 0
  major version: 58
  flags: (0x0020) ACC_SUPER
  this_class: #1                          // Point
  super_class: #3                         // java/lang/Object
  interfaces: 0, fields: 2, methods: 1, attributes: 1
...
{
  public int x;
    descriptor: I
    flags: (0x0001) ACC_PUBLIC

  public int y;
    descriptor: I
    flags: (0x0001) ACC_PUBLIC
...

Since it knows there are two fields, both of type int ( descriptor: I ), it knows exactly how much memory will be needed.

Tried to write the comment, but it's too long.

This line:

Point x = new Point();

could be broken into three parts:

  1. variable declaration: Point x
  2. assignment: =
  3. object instantiation: new Point()

Part 3 (object instantiation) leads to memory allocation and instance initialization. Only part 3 defines which object you want to allocate ( new Point() , new Circle() , etc). Since runtime knows about type, it can calculate amount of memory required.

Part 1 (variable declaration) just tells the rest of code, how it can access newly allocated object, so, types from the left and from the right of assignment operator = may differ.

If both Point and Circle will inherit the same base class Drawing , then in C# you can write:

Drawing x = new Point();

This sample still allocates point because of new Point() , but the rest of code can use the point only as base class instance, Drawing , eg:

x.Draw();

and cannot use it as Point without cast:

x.x = 100; // compile time error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM