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

前端 未结 5 1946
渐次进展
渐次进展 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:23

    Instance scope versus class scope.

    Check this out:

    class Foobar {
      public final int x = 5;
      public static final int y = 6;
    }
    

    y is a variable that is only created once, at compile time. It is bound to the class, and therefore shared by all of its instances. You reference this with Foobar.y.

    System.err.println(Foobar.y);
    

    x on the other hand, is an instance variable, and every Foobar that you create with new will have a copy of it. You would reference it like this:

    Foobar foobar = new Foobar();
    System.err.println(foobar.x);
    

    But this will not work:

    System.err.println(Foobar.x);
    

提交回复
热议问题