Java code snippet output explanation required

后端 未结 4 1364
北恋
北恋 2020-12-03 02:03

My code is:

class Foo {
  public int a=3;
  public void addFive() {
    a+=5;
    System.out.print(\"f \");
  }
}

class Bar extends Foo {
  public int a=8;
         


        
4条回答
  •  时光说笑
    2020-12-03 02:12

    You cannot override variables in Java, hence you actually have two a variables - one in Foo and one in Bar. On the other hand addFive() method is polymorphic, thus it modifies Bar.a (Bar.addFive() is called, despite static type of f being Foo).

    But in the end you access f.a and this reference is resolved during compilation using known type of f, which is Foo. And therefore Foo.a was never touched.

    BTW non-final variables in Java should never be public.

提交回复
热议问题