问题
I have two classes Test
and Encap
. I have a private variable a
and access via setter and getter method. and i'm inheriting the class Test
with Encap
.
now i am able to change the value of a
using setValue(int a)
. i want to restrict that option. i want it to make it as a read only value. please assist me in this.
class Test
{
private int a;
protected void setValue(int a)
{
this.a = a;
}
protected void getValue()
{
System.out.println("The assigned value of a is : "+this.a);
}
}
public class Encap extends Test {
public static void main(String [] args)
{
Test t = new Test();
t.setValue(4);
t.getValue();
Encap e = new Encap();
e.setValue(3);
e.getValue();
}
}
回答1:
One option would be to delete the method setValue()
from the class Test
:
class Test
{
private int a;
protected void getValue()
{
System.out.println("The assigned value of a is : "+this.a);
}
}
Edit:
Why to do this? If Encap
inherits from Test
, it should be able to do the same actions as Test
. Otherwise, what's the purpose of inheriting? If you still thinking that Test
should be able to modify the value and Encap
not, maybe your design is wrong. You could try something like this instead:
BaseClass
---------
+getValue
/ \
/ \
Test Encap
-------- ---------
+setValue
回答2:
If you mean that you want a derived class to not expose public methods of the superclass, then your code probably 'smells'...
Remember that Inheritance models "Is A"
So in your example an Encap is a Test and you should be able to do anything to an Encap that you can do to a Test.
However, if you simply must inherit from a class where you don't want to expose a parent-class method, you can override the method and have its body do nothing. But for simple getter and setter accessor methods this is potentially very confusing for clients of your code.
If you can't reconcile things and calling setValue() on an Encap is never the right thing to do, i would recommend overriding the method, commenting it liberally and have it do nothing, or throw an exception to indicate to the client that they're doing something that doesn't make sense.
来源:https://stackoverflow.com/questions/23863040/how-to-achieve-encapsulation-in-inheritance