为什么 HashSet 类型的私有变量在类的对象实例之间共享?

问题描述 投票:0回答:1

我最近偶然发现了 Java 的这种奇怪行为,其中在父类中声明为私有的 Hashset 类型的变量对于子类的每个实例来说并不是唯一的。相反,所有实例都指向同一个私有变量,并且对一个实例的修改会反映到所有实例。 但是,如果我们有来自同一父级继承的两个类的实例,那么它是唯一的。

请查看下面的类结构。

Public Class Main { 
private Set<String> test = new HashSet();
protected void addToTest (String s){test.add(s);} 
}

Public Class Child1 extends Main { }

Public Class Child2 extends Main{ }

如果我们有同一个类的两个实例继承主类。

Main o1 = new Child1(); 
Main o2 = new Child1();

o1.addToTest("test"); 
o2.addToTest("test");

o1.clear();
//If we clear from one object is clearing at both the places, and both the object's hashcode of the variable test is same.

如果我们有两个继承主类的不同类的实例。

Main o1 = new Child1(); 
Main o2 = new Child2();

o1.addToTest("test");
o2.addToTest("test");

o1.clear();
//If we clear from one object is not clearing at both the places, and both the object's hashcode of the variable test is different

有人可以帮助我理解为什么行为不同吗?另外,我假设如果一个变量被声明为私有,它对于该实例应该是唯一的,但这里不是;

为什么这里的实例变量不唯一?

java set private hashset instance-variables
1个回答
0
投票

test
变量是一个实例变量,这意味着
Main
Child1
Child2
的每个实例都有自己的测试变量。考虑到您初始化测试的方式,它们都将拥有自己独特的
HashSet
对象。这就是实例变量的工作原理。

如果您希望对象共享

HashSet
,则必须从外部传入该集合(例如通过构造函数参数),或者您需要将 test 设置为静态变量。

注意:使用

static
并不是很OO,它会导致各种实际问题。您的应用程序越大,
static
状态的问题就越大。

© www.soinside.com 2019 - 2024. All rights reserved.