Home > Java > javaTutorial > How Can You Simulate C 's 'friend' Concept in Java?

How Can You Simulate C 's 'friend' Concept in Java?

Susan Sarandon
Release: 2024-11-11 05:48:03
Original
430 people have browsed it

How Can You Simulate C  's 'friend' Concept in Java?

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.

  1. Juliet's cuddle method becomes public but requires a Romeo.Love argument:
public static void cuddle(Romeo.Love love) {
    if (love == null) throw new NullPointerException();
    System.out.println("O Romeo, Romeo, wherefore art thou Romeo?");
}
Copy after login
  1. Romeo defines a public static nested class Love with a private constructor:
public static final class Love { private Love() {} }
Copy after login

Only Romeo can construct a Romeo.Love instance. Romeo then creates a static final Romeo.Love reference:

private static final Love love = new Love();
Copy after login
  1. Romeo's cuddleJuliet method:
public static void cuddleJuliet() {
    Juliet.cuddle(love);
}
Copy after login

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!

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