按类引用字段和按对象调用字段有什么区别? [英] What is the difference between referencing a field by class and calling a field by object?

查看:160
本文介绍了按类引用字段和按对象调用字段有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到有时用Java编写我见过的方法调用字段:

I have noticed that there are times when coding in Java that I have seen fields called by method:

System.out.println(object.field);

和按类:

System.out.println(Class.field);

我的教科书中没有看到任何关于这两种情况的语义是什么的明显区别,以及我担心,至少对于一个菜鸟来说,这将是一个微妙的观点。我的直觉是类调用将用于静态字段?多谢你们。这么多con'foo'sion。

I have not seen any clear distinguishing in my textbooks about what the semantics are for these two cases, and I fear that it is going to be, at least for a noob, a subtle point. My intuition is that the class calling will be used for static fields? Thanks guys. So much con'foo'sion.

推荐答案

字段 Class.field 无需创建类的实例即可访问。这些是 static 字段,这些字段在类加载器加载时初始化。

The field Class.field can be accessed without creating an instance of the class. These are static fields which are initialized when the classes are loaded by classloaders.

另一个字段即<$ c只有在创建类的实例时才能访问$ c> object.field 。这些是通过调用其构造函数创建类的对象时初始化的 instance 字段。

The other field i.e. object.field can be accessed only when an instance of the class is created. These are instance field initialized when object of the class is created by calling its constructor.

这篇关于按类引用字段和按对象调用字段有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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