overriding a variable in java

前端 未结 4 1343
我寻月下人不归
我寻月下人不归 2020-12-11 14:32
public class Foo {
      public int a = 3;
    public void addFive(){
        a += 5; System.out.print(\"f \");
    }
}

public class          


        
4条回答
  •  醉话见心
    2020-12-11 15:09

    Declaring public int a = 8 in Foo class instead of Bar class it should work... printing B 3.

    But I suppose you are talking about a question included in the Java certification exam, so you have to correct the code of the Foo class adding public int a = 3.

    You cannot override a variable in Java, but declaring in as public (or protected) in the super-class you can use it also in all inherited classes.

    In this case the right output is B 13 because in the test class you are using a Bar object as a Foo object, so the value of a is 3 and not 8.

提交回复
热议问题