Java-like friends class mechanism

Do you guys know how I can make an object mutable only inside a special class? In this example, I want the PrivateObject to be only mutable (expandable) inside the Box class, nowhere else. Is there any way to get this?

public class Box { private PrivateObject prv; public void setPrivateObject(PrivateObject p){ prv = p; } public void changeValue(){ prv.increment(); } } public class PrivateObject { private value; public increment(){ value++; } } PrivateObject priv = new PrivateObject (); Box box = new Box(); box.setPPrivateObject(priv); box.changevalue(); priv.increment(); //i dont want it to be changable outside the Box class! 

In C ++, I would make all the properties and methods of PrivateObject private and declare the Box class as a friend for the PrivateObject class.

+6
source share
4 answers

If PrivateObject strongly tied to Box , why not make it an inner class inside Box ?

 class Box { public static class PrivateObject { private value; private increment(){ value++; } } private PrivateObject prv; public void setPrivateObject(PrivateObject p){ prv = p; } public void changeValue(){ prv.increment(); } } 

Now you cannot call increment from outside Box :

 public static void main(String args[]) { Box.PrivateObject obj = new Box.PrivateObject(); Box b = new Box(); b.setPrivateObject(obj); obj.increment(); // not visible } 
+3
source

The closest would be to make PrivateObject an inner class of Box and make increment private. Thus, the method will be available only in the Box class.

 public class Box { private PrivateObject prv; public void setPrivateObject(PrivateObject p) { prv = p; } public void changeValue() { prv.increment(); } public static class PrivateObject { private int value; private void increment() { value++; } } } 

If you do not want to do this, the next option would be to make a private increment package and find 2 classes in one package. Thus, only classes inside this package will have access to this method. But this may include classes other than Box.

+3
source

In Java, there is no language function equivalent to a keyword with C ++ keywords. However, there are a number of application level alternatives:

  • Declare the increment() method of the PrivateObject class as private-package and define Box in the same package.

OR

2. Set the calling code to pass the token to increment() - inside this method check whether this token is from the Box class and enable or disable.

The idea is to keep the connection between the PrivateObject and Box classes managed.

+3
source

In Java, you create a group of β€œfriends” by putting several classes in the same package. Then use the default classes (without an access specifier) ​​for the classes, methods, and fields for which you want to restrict access.

+1
source

Source: https://habr.com/ru/post/917169/


All Articles