Home  >  Article  >  Java  >  Can Java Mimic C 's "friend" Concept?

Can Java Mimic C 's "friend" Concept?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 08:42:01291browse

Can Java Mimic C  's

Can Java Emulate C 's 'friend' Concept?

In C , the 'friend' concept allows classes from different packages to access private and protected methods of other classes. In Java, there is no direct equivalent to this feature. However, a clever workaround can simulate the 'friend' concept.

How to Simulate 'friend' in Java

The key to this workaround is using a class-level secret identifier. Let's imagine we have two classes from different packages: Romeo and Juliet. Romeo wants to access Juliet's non-public methods without extending her class.

In Romeo's package:

public class Romeo {
    public static final class LoveIdentifier {
        private LoveIdentifier() {}
    }
    private static final LoveIdentifier loveIdentifier = new LoveIdentifier();
    
    public void cuddleJuliet(Juliet.LoveIdentifier loveIdentifier) {
        // ...
    }
}

Romeo defines a nested static class LoveIdentifier with a private constructor. This class serves as the secret identifier that allows Romeo access to Juliet's private methods.

In Juliet's package:

public class Juliet {
    public static final class LoveIdentifier {
        private LoveIdentifier() {}
    }
    private static final LoveIdentifier loveIdentifier = new LoveIdentifier();
    
    public void beCuddled(Romeo.LoveIdentifier loveIdentifier) {
        // Allow Romeo to access private methods using the identifier
    }
}

Juliet also defines an identical LoveIdentifier class to match Romeo's. When Juliet's beCuddled method is called, it checks if the LoveIdentifier passed matches her own. If it does, it grants Romeo access to its private methods.

Using the 'Friend' Simulation

Now, Romeo can interact with Juliet by providing the shared LoveIdentifier as an argument:

Romeo romeo = new Romeo();
Juliet juliet = new Juliet();
romeo.cuddleJuliet(juliet.loveIdentifier);

Since Romeo is passing the correct LoveIdentifier, he can access Juliet's private methods, effectively simulating the C 'friend' relationship.

The above is the detailed content of Can Java Mimic C 's "friend" Concept?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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