开发者

Java-Instance Method Call

When I call as instance method of a class as follows : objec开发者_运维技巧t_name.function_name(); how the compiler knows that the "function_name" has to be called for that "object_name" behind the scenes ?


This is determined by the compiler as it reads your code. Java has a syntax which defines the rules and grammar of the language. Java's particular syntax dictates that object references can be followed by a dot and then a method name.

All languages (not just programming languages) have similar rules. Your brain is compiling the sentence you are reading now based on the syntax of the English language. The rules of the language are what makes it possible for the language to be understood. By defining rules about the meaning of expressions, we are able to communicate. Programming languages are no different!


When the compiler reads the code, its pushing each "word" (anything between whitespace or operators) into an internal stack. When it finds an operator such as "+", "=", or ".", it then pops the last "word" from the stack. The compile knows that the "." operator means you are calling a method from an object who's name is the word you just popped off. It then looks for that object's class file for the method.

For example:

Object object_name = new Object();

object_name.function_name();

When the compile gets to the line above, it pushes object_name into the internal stack, and then look for a method named function_name() inside the Object.class file. If it doesn't find an Object.class file, it will look for an Object.java file and will compile that and then look for function_name() within the newly compile Object.class file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜