java - Set current instance to a different instance of the same object -


is there way within instance method of class change current instance pointing to?

this tried far:

public class test {      string name;     test other;      public test(string name) {         this.name = name;     }      public void setother(test test) {         this.other = test;     }      public void printname(){         system.out.println(this.name);     }      public void testmeout(){         changeinstance(this, other);         printname();     }      public static void changeinstance(test instance1, test instance2) {         instance1 = instance2;     } } 

and class testing test class:

public class testingtest {     public static void main(string[] args) {         test test1 = new test("test1");         test1.setother(new test("test2"));         test1.testmeout();         test1.printname();     } } 

i expected output "test2" bother printname() methods print out "test1"

since object being passed in reference shouldn't first instance become second instance? there way possible?

there no way can in java. instance instance is, it’s called identity sometimes. if can explain reason why want this, there other way obtain functionality you’re after. instance, it’s possible , normal object delegate method calls other object.

inside changeinstance method references instance1 , instance2 local method only, putting new reference instance1 has no effect outside method.

an example:

public class test {      string name;     /** delegate */     test other = null;      public test(string name) {         this.name = name;     }      public void setother(test test) {         this.other = test;     }      public void printname(){         if (other == null) { // no delegate, own work             system.out.println(this.name);         } else {             // delegate other             other.printname();         }     }  } 

now if change main method to:

public static void main(string[] args) {     test test1 = new test("test1");     test1.printname();     test1.setother(new test("test2"));     test1.printname(); } 

it print:

test1 test2 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -