从内存中的对象访问静态变量(Accessing static variable from an object in memory)

编程入门 行业动态 更新时间:2024-10-23 15:29:54
从内存中的对象访问静态变量(Accessing static variable from an object in memory)

最近,我了解到除了类名之外,还可以从对象访问静态变量。

我相信静态变量驻留在堆中的永久生成区域中,而不是堆中的对象相关区域中。

另外,我认为m1.count指的是m1的内存位置,并添加一些偏移量来访问count实例变量。

在我的逻辑中, m1.count应该吐出错误,因为在内存中m1对象附近没有名为count的实例变量。

怎么可能呢? 我想知道它在内存中是如何工作的。 这是代码:

class Member{ public static int count; } public static void main(){ Member m1 = new Member(); System.out.println(m1.count); // ??? }

Recently, I learned that the static variable could be accessed from an object, in addition to a class name.

I believe that static variables reside in the permanent generation area in the heap, not in the object related area in the heap.

Also, I think that m1.count refers the memory position of m1, and add some offset to access the count instance variable.

In my logic, m1.count should spit error since there is no instance variable called count near m1 object in memory.

How could it be possible? I want to know how it works in memory. Here is the code:

class Member{ public static int count; } public static void main(){ Member m1 = new Member(); System.out.println(m1.count); // ??? }

最满意答案

我相信静态变量驻留在堆中的永久生成区域,

这样的静态字段可以在堆上的任何位置。

我认为m1.count是指m1的内存位置,

static字段忽略引用。 引用可以为null ,代码运行正常。

我想知道它在内存中是如何工作的

该类的static字段有一个特殊对象。 您可以使用堆转储获取此信息。 该引用是偶然的。

这个

Member m1 = new Member(); System.out.println(m1.count);

是相同的

Member m1 = null; System.out.println(m1.count);

这是一样的

System.out.println(Member.count);

I believe that static variables reside in the permanent generation area in the heap,

such static fields can be anywhere on the heap.

I think that m1.count refers the memory position of m1,

static fields ignore the reference. The reference can be null and the code will run fine.

I want to know how it works in memory

There is a special object for the static fields of the class. You can get this the with a heap dump. The reference is incidental.

This

Member m1 = new Member(); System.out.println(m1.count);

is the same as

Member m1 = null; System.out.println(m1.count);

which is the same as

System.out.println(Member.count);

更多推荐

本文发布于:2023-07-15 19:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117540.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   静态   对象   内存   Accessing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!