Reputation: 2345
If I have a class that can't be changed (inside a jar), Ex.
public class AA implements A{
private String s = "foo";
public String getValue() { return s; }
}
what would be a good way to override that getValue() method? My way has been recopying the class. Ex.
public class AB implements A{
private String s = "foo";
public String getValue() { return s + "bar"; }
}
Thanks!
Upvotes: 1
Views: 2792
Reputation: 21449
There are two ways of fixing this:
1) Using inheritance.
public B extends A{
public String getValue(){
String s = super.getValue();
// do something with s
return s;
}
}
This will work fine but users can still cast B
to A
as B
inherits from A
. Which means that you can still access A.getValue()
from a class B
and that's not what you want.
2) The other solution is to use the Adapter pattern
public B {
private A a = new A();
public String getValue(){
String s = a.getValue();
// do something with s
return s;
}
}
This way, B
uses A
and hides it. No casts of B
to A
will be possible and no calls to A.getValue()
would be available.
Upvotes: 4
Reputation: 120308
No matter what you do, you cant get access to the private variable (without reflection). If you needs its value, invoke the superclass's getter in your getter, to get the value, then manipulate it as you will. You can invoke the superclass's method by doing
super.getValue();
inside your getValue
implementation.
Given your update
public class AB extends AA {
public String getValue() {
String superS = super.getValue();
return superS + "bar";
}
}
Note the following
1) Im using extends
which you do not. extends
is for extending a class, implements
is for implementing an interface.
2) Im not shadowing s
. I'm leaving that in the super class. I just use the super's getValue
in conjunction what the decoration you specified.
Upvotes: 5
Reputation: 33544
Thats what Encapsulations are for... Your example points at Design principle named as OCP (Open Closed Principle).
That means Classes are open for extension, and not for modifications. You can use the jars methods to access its private variables, but cannot modify it in a illegal way.
You can access the private variable in the super-class, by only accessing the super-class's getter method.
Upvotes: 0