Home > Backend Development > C++ > How Can Java Mimic C 's Friend Class Functionality?

How Can Java Mimic C 's Friend Class Functionality?

Patricia Arquette
Release: 2024-12-24 16:53:22
Original
590 people have browsed it

How Can Java Mimic C  's Friend Class Functionality?

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
    }
}
Copy after login

In this example:

  • Juliet.cuddleAllowed is a nested class with a private constructor. Only Juliet can instantiate it.
  • Juliet.cuddle() is private but can be accessed internally or from Juliet.CuddleAllowed instances.
  • Romeo uses the cuddleAllowed instance to access cuddle(). Juliet will cuddle only if the instance is provided by Romeo.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template