方法如何在运行时查找其对象的实例变量 [英] How does a method find the instance variables of its object at runtime

查看:77
本文介绍了方法如何在运行时查找其对象的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建对象并调用其公共方法之一时,它可以使用局部属性.它们存储在哪里?我的意思是,在像C这样的语言中,这很清楚:要使用的变量必须作为参数传递给函数(或者必须是全局的).

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).

在Java(可能还有其他OO语言)中会发生什么?本地方法如何使用实例的属性?

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

简而言之:当我们说this.variable时,方法如何找到自己的变量?是"this"指针作为函数参数隐式传递吗?

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

推荐答案

您是对的:每个实例方法都是一个函数,该函数声明的参数比显式声明的参数多.第一个参数始终是隐式this引用(指针). Java的语法仅掩盖了这一点:

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)

只是另一种写作方式

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.

这篇关于方法如何在运行时查找其对象的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆