如果父类(super class)具有 protected Hashmap 变量,如何在不使用 getter 和 setter 方法的情况下阻止子类的修改访问?
这个映射是可变的(所以我应该能够添加父类(super class)中的值)所以不能使用UnmodifyingMap(它唯一适用的不可变集合对象)
Class A
{
protected Map<Integer,Integer> m = new HashMap<Integer,Integer>();
A()
{
m.put(10,11)
m.put(11.12)
}
}
Class B extends A
{
B()
{
super.m.put(34,90) —— I don’t want to give access to child class to add
值和子类及其唯一应该能够获取值。 } }
最佳答案
使 map 不可修改,并在 A 的构造中填充它。
class A {
protected final Map<Integer,Integer> m;
A() {
Map<Integer, Integer> tempMap = = new HashMap<>();
tempMap.put(10,11);
tempMap.put(11.12);
this.m = java.util.Collections.unmodifiableMap(tempMap);
}
}
如果 B 尝试修改 map ,则会抛出“UnsupportedOperationException”。
如果您希望 A 能够修改映射,那么您将需要一种不同的方法,其中映射是私有(private)的,并且 protected getter 返回不可修改的映射。
class A {
private final Map<Integer,Integer> m = new HashMap<>();
A() {
m.put(10,11);
m.put(11.12);
// m remains modifiable within the context of A
}
protected Map<Integer, Integer> getMap() {
return java.util.Collections.unmodifiableMap(m);
}
}
编辑
如果您确实不想使用 getter 但仍具有只读访问权限,则可以使用此方法。
class A {
private final Map<Integer,Integer> writableMap = new HashMap<>();
protected final Map<Integer,Integer> m = Collections.unmodifiableMap(writableMap);
A() {
writableMap.put(10,11);
writableMap.put(11.12);
}
}
使用这种方法,只有m
在A外部可见,并且是只读的。在 A 中,您可以更新 writableMap
并且这些更改将在 m
关于java - 在java中不使用getter和setter的情况下防止子类访问 protected 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29840657/