Friend classes in java

Implementation of Friend concept in Java [duplicate]

This can be achieved using the ‘Friend Accessor’ pattern as detailed below: The class exposed through the API: The class providing the ‘friend’ functionality: Example access from a class in the ‘friend’ implementation package: Solution 4: There are two solutions to your question that don’t involve keeping all classes in the same package. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients.

Implementation of Friend concept in Java [duplicate]

How does one implement the friend concept in Java (like C++)?

Java does not have the friend keyword from C++. There is, however, a way to emulate that; a way that actually gives a lot more precise control. Suppose that you have classes A and B. B needs access to some private method or field in A.

public class A < private int privateInt = 31415; public class SomePrivateMethods < public int getSomethingPrivate() < return privateInt; >private SomePrivateMethods() < >// no public constructor > public void giveKeyTo(B other) < other.receiveKey(new SomePrivateMethods()); >> public class B < private A.SomePrivateMethods key; public void receiveKey(A.SomePrivateMethods key) < this.key = key; >public void usageExample() < A anA = new A(); // int foo = anA.privateInt; // doesn't work, not accessible anA.giveKeyTo(this); int fii = key.getSomethingPrivate(); System.out.println(fii); >> 

The usageExample() shows how this works. The instance of B doesn’t have access to the private fields or methods of an instance of A. But by calling the giveKeyTo(), class B can get access. No other class can get access to that method, since it a requires a valid B as an argument. The constructor is private.

The class B can then use any of the methods that are handed to it in the key. This, while clumsier to set up than the C++ friend keyword, is much more fine-grained. The class A can chose exactly which methods to expose to exactly which classes.

Now, in the above case A is granting access to all instances of B and instances of subclasses of B. If the latter is not desired, then the giveKeyTo() method can internally check the exact type of other with getClass(), and throw an exception if it is not precisely B.

Suppose A.foo() should only be called by B . This can be arranged by a token that can only be generated by B .

public class B < public static class ToA < private ToA()<>> private static final ToA b2a = new ToA(); void test() < new A().foo(b2a); >> public class A < public void foo(B.ToA b2a) < if(b2a==null) throw new Error("you ain't B"); // . >> 

Only B can generate a non-null B.ToA token. If both A and B do not leak this token to the 3rd party, nobody else can invoke A.foo()

If A2 wants to friend B too, it needs a different token type. If it’s the same token type, since A got a token of the type from B , A can pretend to be B to A2 .

The check is done at runtime, not compile time, that is not perfect. Not a big deal though, since any 3rd party can only invoke A.foo() with a null , it can’t be an innocent mistake which we want to check at compile time; it’s probably malicious so we don’t care to warn the caller at compile time.

In Java you can put both (or more) classes into the same package. All methods and fields with the protected qualifier can directly be accessed by all classes in that package.

Читайте также:  CSS шрифты и примеры их форматирования

I figured out another way to achieve the same. Basically you check the fully qualified name of the invoking class name. If it matches your «friend» function, then you give access, else you return null.

public class A < private static int privateInt = 31415; public static int getPrivateInt() < if(Throwable().getStackTrace()[1].getClassName().equals(new String("example.java.testing.B"))) < return privateInt; >else < return null; >> > package example.java.testing; public class B < public void usageExample() < int foo = A.getPrivateInt; // works only for B System.out.println(foo); >> 

Virtual Function in Java, Virtual Function in Java. A virtual function or virtual method in an OOP language is a function or method used to override the behavior of the function in an inherited class with the same signature to achieve the polymorphism. When the programmers switch the technology from C++ to Java, they think about where is …

Is there a way to simulate the C++ ‘friend’ concept in Java?

I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?

Here is a small trick that I use in JAVA to replicate C++ friend mechanism.

Lets say I have a class Romeo and another class Juliet . They are in different packages (family) for hatred reasons.

Romeo wants to cuddle Juliet and Juliet wants to only let Romeo cuddle her.

In C++, Juliet would declare Romeo as a (lover) friend but there are no such things in java.

Here are the classes and the trick :

package capulet; import montague.Romeo; public class Juliet < public static void cuddle(Romeo.Love love) < Objects.requireNonNull(love); System.out.println("O Romeo, Romeo, wherefore art thou Romeo?"); >> 

So the method Juliet.cuddle is public but you need a Romeo.Love to call it. It uses this Romeo.Love as a «signature security» to ensure that only Romeo can call this method and checks that the love is real so that the runtime will throw a NullPointerException if it is null .

package montague; import capulet.Juliet; public class Romeo < public static final class Love < private Love() <>> private static final Love love = new Love(); public static void cuddleJuliet() < Juliet.cuddle(love); >> 

The class Romeo.Love is public, but its constructor is private . Therefore anyone can see it, but only Romeo can construct it. I use a static reference so the Romeo.Love that is never used is only constructed once and does not impact optimization.

Therefore, Romeo can cuddle Juliet and only he can because only he can construct and access a Romeo.Love instance, which is required by Juliet to cuddle her (or else she’ll slap you with a NullPointerException ).

The designers of Java explicitly rejected the idea of friend as it works in C++. You put your «friends» in the same package. Private, protected, and packaged security is enforced as part of the language design.

James Gosling wanted Java to be C++ without the mistakes. I believe he felt that friend was a mistake because it violates OOP principles. Packages provide a reasonable way to organize components without being too purist about OOP.

NR pointed out that you could cheat using reflection, but even that only works if you aren’t using the SecurityManager. If you turn on Java standard security, you won’t be able to cheat with reflection unless you write security policy to specifically allow it.

The ‘friend’ concept is useful in Java, for example, to separate an API from its implementation. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients. This can be achieved using the ‘Friend Accessor’ pattern as detailed below:

Читайте также:  Php what url was requested

The class exposed through the API:

package api; public final class Exposed < static < // Declare classes in the implementation package as 'friends' Accessor.setInstance(new AccessorImpl()); >// Only accessible by 'friend' classes. Exposed() < >// Only accessible by 'friend' classes. void sayHello() < System.out.println("Hello"); >static final class AccessorImpl extends Accessor < protected Exposed createExposed() < return new Exposed(); >protected void sayHello(Exposed exposed) < exposed.sayHello(); >> > 
package impl; public abstract class Accessor < private static Accessor instance; static Accessor getInstance() < Accessor a = instance; if (a != null) < return a; >return createInstance(); > private static Accessor createInstance() < try < Class.forName(Exposed.class.getName(), true, Exposed.class.getClassLoader()); >catch (ClassNotFoundException e) < throw new IllegalStateException(e); >return instance; > public static void setInstance(Accessor accessor) < if (instance != null) < throw new IllegalStateException( "Accessor instance already set"); >instance = accessor; > protected abstract Exposed createExposed(); protected abstract void sayHello(Exposed exposed); > 

Example access from a class in the ‘friend’ implementation package:

package impl; public final class FriendlyAccessExample < public static void main(String[] args) < Accessor accessor = Accessor.getInstance(); Exposed exposed = accessor.createExposed(); accessor.sayHello(exposed); >> 

There are two solutions to your question that don’t involve keeping all classes in the same package.

The first is to use the Friend Accessor/Friend Package pattern described in (Practical API Design, Tulach 2008).

The second is to use OSGi. There is an article here explaining how OSGi accomplishes this.

Related Questions: 1, 2, and 3.

Friend class and function in C++, 1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming. 2) Friendship is not mutual.

C++-like friend class mechanism in Java

Do you know how can I make an object changeable only inside a special class? In this example I want the object PrivateObject to be only changable (incrementable) inside the Box class, nowhere else. Is there a way to achieve this?

public class Box < private PrivateObject prv; public void setPrivateObject(PrivateObject p)< prv = p; >public void changeValue() < prv.increment(); >> public class PrivateObject < private value; public increment()< value++; >> PrivateObject priv = new PrivateObject (); Box box = new Box(); box.setPPrivateObject(priv); box.changevalue(); priv.increment(); // I don't want it to be changeable outside the Box class! 

In C++, I would make all the PrivateObject properties and methods private, and the declare the Box class as a friend for the PrivateObject class.

If PrivateObject is strongly related to Box why not make it an inner class inside Box ?

class Box < public static class PrivateObject < private value; private increment()< value++; >> private PrivateObject prv; public void setPrivateObject(PrivateObject p) < prv = p; >public void changeValue() < prv.increment(); >> 

Now you cannot call increment from outside Box :

public static void main(String args[]) < Box.PrivateObject obj = new Box.PrivateObject(); Box b = new Box(); b.setPrivateObject(obj); obj.increment(); // not visible >

The closest would be to make PrivateObject an inner class of Box and make increment private. That way, the method will be accessible only within the Box class.

public class Box < private PrivateObject prv; public void setPrivateObject(PrivateObject p) < prv = p; >public void changeValue() < prv.increment(); >public static class PrivateObject < private int value; private void increment() < value++; >> > 

If you don’t want to do that, the next option would be to make increment package private and locate the 2 classes in the same package. That way, only classes within that package will have access to that method. But that might include classes other than Box.

Java does not have any language feature equivalent of C++’s friend keyword. However , there are number of application-level alternatives :

  1. Declare the increment() method of the PrivateObject class as package- private and define Box in the same package.
Читайте также:  Live Mysql Data Search using javaScript with PHP

2.Let the calling code pass a token into increment() — inside this method check if this token is indeed coming from Box class and allow or disallow.

The idea is to keep the coupling between PrivateObject and Box class manageable.

In Java, you would create a group of «friends» by putting multiple classes in the same package. Then, use default scope (no access specifier) on the classes, methods and fields you want to restrict access to.

Examples of Function Overloading in Java, Introduction to Function Overloading in Java. Function Overloading in Java occurs when there are functions having the same name but have different numbers of parameters passed to it, which can be different in data like int, double, float and used to return different values are computed inside the respective …

Источник

Friend Class in Java

Friend Class in Java

Friend class is the functionality of C++, which is used to access the non-public members of a class. Java doesn’t support the friend keyword, but we can achieve the functionality.

This tutorial demonstrates how to create a friend class in Java.

Friend Class in Java

The friend concept can also be implemented in Java. For example, two colleagues from different departments of a company.

Both colleagues don’t know each other, but they need to cooperate for some work. Let’s set one employee as Jack and the other as Michelle based on a friend pattern.

We need to create two packages and implement both classes to implement this example.

The class Jack in Department(package) Delftstack1 :

package Delftstack1;  import Delftstack2.Michelle;  public final class Jack   static   // Declare classes in the Delftstack2 package as 'friends'  Michelle.setInstance(new Michelle_Implement());  >   // Constructor is Only accessible by 'friend' classes.  Jack()    >   // This Method is Only accessible by 'friend' classes.  void HelloDelftstack()   System.out.println("Hello! I am Jack from Delftstack");  >   static final class Michelle_Implement extends Michelle   protected Jack createJack()   return new Jack();  >   protected void sayHello(Jack jack)   jack.HelloDelftstack();  >  > > 

The class Michelle in Department(package) Delftstack2 :

package Delftstack2;  import Delftstack1.Jack;  public abstract class Michelle    private static Michelle instance;   static Michelle getInstance()   Michelle a = instance;  if (a != null)   return a;  >   return createInstance();  >   private static Michelle createInstance()   try   Class.forName(Jack.class.getName(), true,  Jack.class.getClassLoader());  > catch (ClassNotFoundException e)   throw new IllegalStateException(e);  >   return instance;  >   public static void setInstance(Michelle michelle)   if (instance != null)   throw new IllegalStateException("Michelle instance already set");  >   instance = michelle;  >   protected abstract Jack createJack();   protected abstract void sayHello(Jack jack); > 

The class to implement the main method:

package Delftstack2;  import Delftstack1.Jack;  public final class Friend_Class   public static void main(String[] args)   Michelle michelle = Michelle.getInstance();  Jack jack = michelle.createJack();  michelle.sayHello(jack);  > > 

The code above implements the friend class functionality in Java with two classes in different packages. Class Michelle acts as a friend class that accesses the class Jack members.

Hello! I am Jack from Delftstack 

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Related Article — Java Class

Источник

Оцените статью