In Java you can't return const references to objects as you can in C++. How can I return a reference to an object that will be able to be modified inside a class but not from outside?
Consider this example:
I have class A with an object from class Slave. The object will be returned and used outside of the class A. Here's a code, I hope the comments help understand the problem.
public class TestReference
{
public static void main(String[] args) {
TestReference tr = new TestReference();
TestReference.A a = tr.new A();
Slave slave = a.getConstSlave();
slave.printName();
a.setSlaveName("New Name");
slave.printName(); // also changes, this is a reference to the object inside class A
slave.setName("Fake name"); //this shouldn't be able to happen, we are making modifications outside class A
slave.printName();
}
private class A {
private Slave slave;
public A() {
this.slave = new Slave("A");
}
public Slave getConstSlave() {
// How to make sure this slave will not be modified outside
// and will keep consistency with this object modifications
// inside the class A
return slave;
}
public void setSlaveName(String name) {
slave.setName(name);
}
}
private class Slave {
private String name;
public Slave(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
public void setName(String name) {
this.name = name;
}
}
}
IMO there is no way to do that in java, like you would do it in C++.
What you could do is create an Interface (e.g. ReadOnlySlave) and return that instead of Slave:
public interface ReadOnlySlave {
public void printname();
}
public class Slave : ReadOnlySlave {
public void printname() { ... }
public void setName() { .... }
}
public ReadOnlySlave getConstSlave() {
return slave;
}
Then you are able to modify the slave inside your class and the change is visible everywhere, but outside they are not able to change anything.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments