What is the difference between referencing a field by class and calling a field by object?

前端 未结 5 1947
渐次进展
渐次进展 2021-01-26 01:56

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

System.out.println(object.field);

and

5条回答
  •  没有蜡笔的小新
    2021-01-26 02:22

    My intuition is that the class calling will be used for static fields

    Yes SomeClass.field can be used only if field is static. In this case you can also access it via reference like someClassRef.field but this code will be changed by compiler to ReferenceType.field anyway. Also it can cause some misunderstandings (it may seem that you are trying to use non-static field) so it is better to use static fields by its class.

    If field is not static then it must belong to some instance so you will have to call it via reference someClassRef.field

提交回复
热议问题