如何在继承中实现封装 [英] how to achieve encapsulation in inheritance
问题描述
我有两个类测试
和 Encap
。我有一个私有变量 a
并通过setter和getter方法访问。我继承了测试
,其中包含 Encap
。
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
.
现在我可以使用 setValue(int a)更改
。我想限制这个选项。我希望它将它作为只读值。请帮助我。 a
的值
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();
}
}
推荐答案
一个选项是删除方法 setValue()
来自类测试
:
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);
}
}
编辑
为什么要这样做?如果 Encap
继承自测试
,它应该能够执行与测试
相同的操作。否则,继承的目的是什么?如果您仍然认为 Test
应该能够修改该值而 Encap
不是,那么您的设计可能是错误的。您可以尝试这样的事情:
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
这篇关于如何在继承中实现封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!