Replicating C 'friend' Concept in Java
In C , the 'friend' concept allows classes in different packages to access non-public members of other classes. Java lacks a direct equivalent, but it provides a clever workaround using nested classes.
Implementation
Consider two classes, Romeo and Juliet, from different packages. Romeo wishes to access Juliet's non-public methods without subclassing her. Here's how to achieve it using nested classes:
// Juliet's package public class Juliet { private void cuddle() { System.out.println("O Romeo, Romeo, wherefore art thou Romeo?"); } // Signature security for cuddle public static class CuddleAllowed { private CuddleAllowed() {} } private static final CuddleAllowed cuddleAllowed = new CuddleAllowed(); public void cuddle(Juliet.CuddleAllowed cuddle) { cuddle(); // Juliet can cuddle herself if (cuddle == cuddleAllowed) { System.out.println("Only Romeo can cuddle Juliet."); } } } // Romeo's package public class Romeo { public static void cuddleJuliet() { Juliet juliet = new Juliet(); juliet.cuddle(Juliet.cuddleAllowed); // Romeo can cuddle Juliet } }
In this example:
The above is the detailed content of How Can Java Mimic C 's Friend Class Functionality?. For more information, please follow other related articles on the PHP Chinese website!