从具有私有变量的类重写方法

fer*_*k86 1 java

如果我有一个无法更改的类(在jar中),Ex.

public class AA implements A{
  private String s = "foo";
  public String getValue() { return s; }
}
Run Code Online (Sandbox Code Playgroud)

什么是覆盖getValue()方法的好方法?我的方式是重新上课.防爆.

public class AB implements A{
  private String s = "foo";
  public String getValue() { return s + "bar"; }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

hvg*_*des 5

无论你做什么,你都无法访问私有变量(没有反射).如果你需要它的值,在你的getter中调用超类的getter来获取值,然后按照你的意愿操作它.您可以通过执行来调用超类的方法

super.getValue();

在您的getValue实施中.

鉴于您的更新

public class AB extends AA {
  public String getValue() { 
      String superS = super.getValue();
      return superS + "bar"; 
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意以下内容

1)我使用extends你没有.extends用于扩展类,implements用于实现接口.
2)我不是影子s.我要离开超级班了.我只是使用超级getValue结合你指定的装饰.