如果我有一个无法更改的类(在jar中), 防爆。
public class AA implements A{
private String s = "foo";
public String getValue() { return s; }
}
什么是覆盖getValue()方法的好方法? 我的方式是重新上课。实施例
public class AB implements A{
private String s = "foo";
public String getValue() { return s + "bar"; }
}
谢谢!
答案 0 :(得分:5)
无论你做什么,你都无法访问私有变量(没有反射)。如果你需要它的值,在你的getter中调用超类的getter来获取值,然后按照你的意愿操作它。您可以通过执行
来调用超类的方法 super.getValue();
在getValue
实施中。
鉴于您的更新
public class AB extends AA {
public String getValue() {
String superS = super.getValue();
return superS + "bar";
}
}
请注意以下内容
1)我使用你没有的extends
。 extends
用于扩展类,implements
用于实现接口
2)我没有遮蔽s
。我把它留在了超级班。我只是将超级getValue
与您指定的装饰结合使用。
答案 1 :(得分:4)
有两种解决方法:
1)使用继承。
public B extends A{
public String getValue(){
String s = super.getValue();
// do something with s
return s;
}
}
这样可以正常使用,但用户仍可以B
投放A
B
A
继承自A.getValue()
。这意味着您仍然可以从班级B
访问public B {
private A a = new A();
public String getValue(){
String s = a.getValue();
// do something with s
return s;
}
}
,而这不是您想要的。
2)另一种解决方案是使用Adapter pattern
B
这样,A
使用B
并隐藏它。不会有A
到A.getValue()
的强制转型,也不会拨打{{1}}。
答案 2 :(得分:0)
这是什么封装适用于...您的示例指向设计原则,名为 OCP(开放封闭原则)。
这意味着类是开放的扩展,而不是修改。您可以使用jars方法访问其私有变量,但不能以非法方式修改它。
只需访问超类的getter方法,就可以访问超类中的私有变量。