Java:始终具有相同内容的对象?

时间:2017-06-03 11:04:12

标签: java

我想用一个例子解释我的问题:

Base.java:

public class Base {

    //NO annotations
    public AnyClass anyObj;

    public Base(){}
}

DerivedOne .java:

public class DerivedOne extends Base{

    @SomeAnnotionsOne
    public AnyClass anyObjWithAnnotations;

    public DerivedOne (AnyClass anyObj){
        this.anyObj = anyObj;
        anyObjWithAnnotations = this.anyObj;
    }
}

DerivedTwo.java:

public class DerivedTwo extends Base {

    //These annoations differ from  @SomeAnnotionsOne
    @SomeAnnotionsTwo
    public AnyClass anyObjWithAnnotations;

    public Derived_Two(AnyClass anyObj){
      this.anyObj = anyObj;
      anyObjWithAnnotations = this.anyObj;
    }
}

所以我只希望anyObjWithAnnotations始终等于anyObj

示例主要内容:

public static void main(String[] args){
   DerivedOne derivedObj = new DerivedOne(new AnyClass());
   derivedObj.anyObj = null;

   if(derivedObj.anyObjWithAnnotations == null){
      System.out.println("anyObjWithAnnotations : is null");
   }  
}

什么都没打印出来。 anyObjnullanyObjWithAnnotations不是。

我的问题:

anyObj是否总是与anyObjWithAnnotations ??

相同

因此,即使我将其中一个设置为null或使用AnyClass创建new的新实例,其他变量也应具有相同的新内容。

修改

更改了整个示例以澄清问题。

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码,我只创建对象1次,然后将其引用分配给第二个对象。这样,如果在一个对象中更改了值,在示例t1中,它也将反映到t2中。

    class Test {
    private int val;

    public Test(int val) {
        this.val = val;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }
}
public class TestSame {
    public static void main(String[] args) {
        Test t1 = new Test(10);
        Test t2=t1;
        System.out.println(t1.getVal());
        System.out.println(t2.getVal());

        t1.setVal(20);

        System.out.println(t1.getVal());
        System.out.println(t2.getVal());

    }
}

O / P: -

10
10
20
20

您还可以检查t1和t2是否具有相同的哈希码值

  System.out.println("t1 hashcode "+ t1.hashCode());
    System.out.println("t2 hashcode "+ t2.hashCode());

答案 1 :(得分:0)

看起来你需要一个单身人士。

public class Singleton {
    private int val = 0;

    public void setVal(int val) {
        this.val = val;
    }
    public static final Singleton INSTANCE = new Singleton();

    private Singleton() { }

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

用法示例:

Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();

s1.setVal(42);

如果单身对你的情况太多,你可以使用方法:

Object obj1 = new Object();
final Object obj2 = obj1;

因为obj2是最终引用 - 您将无法更改(重新分配)它。因此,obj2obj1将引用相同的Object实例。但是可以重新分配obj1引用。如果您final obj1obj2都设置了final Object obj1 = new Object(); final Object obj2 = obj1; ,那么您将获得您想要的内容。

Using system.IO;
                //Actual downloaded path
if(file.exist (@"c:\folder1\Test.jpg"))
{
   //move file to another directory
   file.Move(@"c:\folder2\Test.jpg")
}