Home > Java > javaTutorial > body text

Can Java Mimic C 's 'friend' Concept?

Susan Sarandon
Release: 2024-11-08 08:42:01
Original
365 people have browsed it

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) {
        // ...
    }
}
Copy after login

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

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);
Copy after login

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!

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