Java code snippet output explanation required

后端 未结 4 1360
北恋
北恋 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:17

    F is a reference of type Foo, and variables aren't polymorphic so f.a refers to the variable from Foo which is 3

    How to verify it?

    To test this you can remove a variable from Foo , it will give you compile time error

    Note: Make member variable private and use accessors to access them


    Also See

    • Why use getters and setters?

提交回复
热议问题