Table of contents
1.
Introduction
2.
Friend Concept in Java
2.1.
Friend Class
2.2.
Friend Function
3.
Friend function vs friend class
4.
Frequently Asked Questions
4.1.
What are keywords in Java?
4.2.
What is a method in Java?
4.3.
What is a class in Java?
4.4.
What is an object in Java?
5.
Conclusion
Last Updated: Dec 9, 2024
Easy

Friend Function in Java

Author Sanchit Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Sometimes, one might think can we implement the friend concept in Java just like in C++ or is it not possible without the friend keyword to access private and protected members of the class and how to implement this friend function in Java?

friend function in java

We will find answers to all such questions in this article on the friend function in Java. 

Read the topic about-  Iteration Statements in JavaDuck Number in Java.

Friend Concept in Java

Java does not have the friend keyword like C++, which is used to access the non-public members of a class. Nevertheless, we can achieve this functionality.

Before we try to implement friend functionality, we need to see what it is precisely in C++ and why we need it, and what we can do using this keyword.

Friend Class

A friend class gets access to private and protected members of another class in which it is declared a friend. When granting access to a class, you need to specify that the access is granted to a class using the 'friend' keyword
friend class xclass;

In the given below example, the the_binary_tree class can access data directly

class Node {
    private: 
    int data;
    int key;
    //...
 
    friend class the_binary_tree;
};
You can also try this code with Online C++ Compiler
Run Code

Note - The friend declaration can go in a class's private, protected or public section. It does not matter where they appear.

Must Read Type Conversion in Java

Friend Function

In C++, a friend function is declared outside a class but can access non-public members of the class, that is, the private and protected members.

Sometimes while programming situation arises when we want two classes to share their members. These members may be the data members of the class, the class functions or function templates. In such cases, we make the friend function to both these classes, which will allow accessing private data members and protected data of members of the class.

Generally, non-member functions cannot access the private members of a particular class. Once declared as the friend function, that function can access these classes' private and protected members.

Now let us try to implement the friend function in Java. 

Consider two persons from different departments of a company.

Both people don't know each other, but they need to cooperate for some work. Let us set one employee as Anna and the other as Jess based on a friend pattern.

We must create two packages and implement both classes to implement this example.
 The class Anna in the department(package) codingninjas1

package codingninjas1;

import codingninjas2.Jess;

public final class Anna {
    static {
        /* Declare classes in the codingninjas2 package as 'friends.' */
        Jess.setInstance(new Jess_Implement());
    }

    /* Constructor is only accessible by 'friend' classes. */
    Anna() {

    }

    /* This method is only accessible by 'friend' classes.*/
    void Hellocodingninjas() {
        System.out.println("Hello! I am Anna from codingninjas.");
    }

    static final class Jess_Implement extends Jess {
        protected Anna createAnna() {
            return new Anna();
        }

        protected void sayHello(Anna anna) {
            anna.Hellocodingninjas();
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

The class Jess in the department(package) codingninjas2

package codingninjas2;

import codingninjas1.Anna;

public abstract class Jess {

    private static Jess instance;

    static Jess getInstance() {
    	Jess a = instance;
        if (a != null) {
            return a;
        }

        return createInstance();
    }

    private static Jess createInstance() {
        try {
            Class.forName(Anna.class.getName(), true,
                Anna.class.getClassLoader());
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(e);
        }

        return instance;
    }

    public static void setInstance(Jess jess) {
        if (instance != null) {
            throw new IllegalStateException("Jess instance already set");
        }

        instance = jess;
    }

    protected abstract Anna createAnna();

    protected abstract void sayHello(Anna anna);
}
You can also try this code with Online Java Compiler
Run Code

The class to implement the main method

package codingninjas2;

import codingninjas1.Anna;

public final class Friend_Class {
    public static void main(String[] args) {
        Jess jess = Jess.getInstance();
        Anna anna = jess.createAnna();
        jess.sayHello(anna);
    }
}
You can also try this code with Online Java Compiler
Run Code

With two classes in different packages, the code above implements the friend class functionality in java. Class Jess acts as a friend class that accesses the class Anna members.

Output

Hello! I am Anna from codingninjas.

Before wrapping up, the article on friend function in java, let's see the difference between friend function and friend class.

Friend function vs friend class

Friend Function

Friend Class

It is a function declared with the 'friend' keyword. It is usually used with operator overloading.It is a class declared with the 'friend' keyword.
The friend function gets access to the private members of the class.Friend class gets access to the protected and private members of the class.
The friend function has to be declared before it is used.It is not necessary to declare a friend class before using it.
Syntax - 
friend returntype xclass::function(args);
Syntax -
friend class xclass;

 

 

Frequently Asked Questions

What are keywords in Java?

Java keywords are reserved terms with a set definition and special function in the java programming language.

What is a method in Java?

In Java, the method refers to the collection of statements grouped to operate. 

What is a class in Java?

A class is a group of objects having common properties. It is a blueprint or template from which objects are created.

What is an object in Java?

An object is an entity that has a state and behaviour. Examples are badminton, strings, grips, shoes, shuttle, etc. It can be physical or logical.

Conclusion

In conclusion, while Java does not have a direct equivalent of the 'friend' keyword found in C++, we can still implement similar functionality by using techniques such as package access and static methods. Through examples like the collaboration between the Anna and Jess classes in different packages, Java can mimic the behaviour of friend functions and classes, allowing access to private and protected members across classes.

We believe this article on the friend function in Java was helpful. You can refer to other similar articles as well - 

Live masterclass