Simulating the C 'friend' Concept in Java
Java does not offer an explicit 'friend' concept as seen in C that allows classes from different packages to access non-public members. However, a clever technique can be employed to replicate this behavior.
Replicating C 'friend' in Java
Consider two classes, Romeo and Juliet, in separate packages. Juliet wants to restrict access to her methods to Romeo. In C , this could be achieved by declaring Romeo as a 'friend' of Juliet.
In Java, a similar effect can be achieved through the use of a private constructor and a static reference.
public static void cuddle(Romeo.Love love) { if (love == null) throw new NullPointerException(); System.out.println("O Romeo, Romeo, wherefore art thou Romeo?"); }
public static final class Love { private Love() {} }
Only Romeo can construct a Romeo.Love instance. Romeo then creates a static final Romeo.Love reference:
private static final Love love = new Love();
public static void cuddleJuliet() { Juliet.cuddle(love); }
Only Romeo can execute Juliet's cuddle method because it has access to the Romeo.Love instance. Other classes cannot instantiate Romeo.Love since its constructor is private.
This technique allows Romeo to access Juliet's cuddle method while restricting access from other classes, effectively simulating the 'friend' concept in Java, where Juliet trusts only Romeo.
The above is the detailed content of How Can You Simulate C 's 'friend' Concept in Java?. For more information, please follow other related articles on the PHP Chinese website!