How does a method find the instance variables of its object at runtime

不打扰是莪最后的温柔 提交于 2020-01-15 04:55:31

问题


When an object is created and one of its public methods is called it can use local attribute. Where are they stored? I mean, in a language like C, it's all clear: variables to be used have to be passed to functions as parameters (or have to be global).

What does it happen in Java (and maybe other OO languages)? How can be instance's attributes used by local methods?

In a nutshell: when we say this.variable, how can a method find its own variable? Is "this" pointer passed implicitly as function parameter?


回答1:


You are right: each instance method is a function which declares one more argument than what is explicitly declared. The first argument is always the implicit this reference (pointer). This is only thinly disguised by Java's syntax:

firstArg.method(secondArg, thirdArg)

is just another way of writing

method(firstArg, secondArg, thirdArg)

And note the special characteristic of the first argument: it is the only one upon whose type the dynamic dispatch of methods takes place.




回答2:


Primitives            → Stack
References to Objects → Stack
Objects               → Heap
Strings               → heap
String Literals       → String Pool (part of heap)



回答3:


It depends on the local variables type. If the variable is an object it will be stored on the Heap, however if it is a primitive it will be stored on the stack.

public class Storage{

   //as fields or instance variables on the object they are also stored on heap
   public int y;  
   public MyObject obj2 = new MyObject();

   public static void main(String[] args){
       Storage storage = new Storage(); //This is an object, it is stored on the heap
   }

   public void do(){
      int x = 1; //stored on stack;
      MyObject obj = new MyObject(); //stored on heap  
   }

}

class MyObject{

}



回答4:


I reckon that one shouldn't forget about escape analysis as well. As it's said in docs,

Escape analysis is a technique by which the Java Hotspot Server Compiler can analyze the scope of a new object's uses and decide whether to allocate it on the Java heap.

(src)

Except, well, that as for now it's not that new



来源:https://stackoverflow.com/questions/20992009/how-does-a-method-find-the-instance-variables-of-its-object-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!