We help IT Professionals succeed at work.

how to implement "friend" access in java ?

eugeneng
eugeneng asked
on
I think doesn't support "friend" access for protected member variable right ? if so, any other way to access a protected, or even private member variable  of a class ?

for example
class a
{
  protected int i;
}
in c, we can do like this,

class B
{
   B()
   {
      A a;
      int i = a.i;
   }
}

class B
{
  friend B;
  protected int i;
}
how to do this is java ? and for some reason, I can do like derive A from B.



Comment
Watch Question

Commented:
I'm not quite sure about your question , but ...
In java if classes are in a same package they can access protected members of class in a same package !
all classes in Java witch is in a same package are "friend" classes !
If A extends B you'll have no problems to access A's ptotected members from B.

Thus:

public class B {
  protected int i;
  // ...
}

public class A extends B {

  //...
  void print() {
    System.out.println("inherited i:"+i);
  }

}
sorry, i meant:

...to access B's ptotected members from A.

Is this what you wanted to know?
No one can access the private members of a class...
Everyone can access the public members and protected members could be accessed by: subclasses and classes from the same package.
If access modifier is not specified it's called "friendly" access - members may be accessed by classes from the same package
The difference between protected and "friendly" access is that:
If A extends B and A and B are in different packages, A cannot access the "friendly access" members of B...

Author

Commented:
I'm sorry this is a mistake in my question, and the last line of my question should be :
"... and for some reason, I CAN'T do like derive A from B."

which is one of the problem i have, I can extent extends A from B.  In C, when B want to access protected member variable of A, we can declare B as "friend" class in A. So from the comments, I guess that we can do that in java, right ?

Author

Commented:
what about "interface", can this be worked around somehow by using convert class B to an interface and ask A to implement B ?
If B is an interface there could not be any implementation of its methods and all its members can be only public (and the fields would be final static as well). Moreover, interfaces have somewhat different semantics...

As to extending classes and implementing interfaces - the major question to be asked in such case is "is A some kind of B" - if the answer is "yes" - it's natural to make A extends/implements B...

So, I don't think this could be your solution.

You may:
1. Make the corresponding B's members public so that every other class could access them (I recommend you this approach);

public class B {
 public int i;
 // ...
 public void doSomething() {
   // ...
 }
}

public class A {
 //...
 void print() {
   B b = new B();
   System.out.println("i:"+b.i);
   b.doSomething();
 }


2. Make the members protected or with the default friendly access and then place A and B classes in the same package.

If these don't fit your situation, would you come with some more details of the A and B classes and their semantics?

Author

Commented:
ok, I'm trying to create my own serializer class, (which is class B), to serialize my own classes object  (class A, and so on...), I will use the reflect class to retrieve the class information (class's fields) and write them to file, by using reflect class's get(..), getInt... etc.. so if I declare all the class's member fields to "private", i will get the IllegalAccessException when I try to retrieve the field value. So currently I use the "A extends B" method, and make all the field to "protected" so my serializer can access the field value. But this doesn't seem to be the correct way, because all my "objects" are not suppose to be a  serializer, but they are "serializable". I know there is a "serialzable" interface in the java, but I'm trying to implement my own way. so I'm wondering if I can use the "friend" way as in C, thus I don't have to extend all my class to the serializer ( which is derived all my classed from serialzer).  

please let me know if there is still an ambiguity about my question...

Oh, I see now. Thanks for the explanation. You are surely right extension isn't a good option.
I would recommend you to use the standard Java object serialization.
You could read about it yourself, but I'll just describe shortly how it should go.
Make you class to implement Serializable and implement these two methods:

 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;

Then you could use ObjectOutputStream's writeObject method to write your class.

For example:
public class Test implements Serializable {
    private int m_age;

 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException {
        out.write(m_age);
        // ...
        out.flush();
     }
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException {
        m_age = in.readInt();
     }
}

And:

      ObjectOutputStream s = new ObjectOutputStream(System.out);
       s.writeObject(new Test()); // would call your private method.

For more details you should see the javadocs on ObjectOutputStream and ObjectInputStream - as well as on the Serializable interface.
Do you still want to be able to access private members of an object? This is not natural in Java...
Have you tried custom serialization as I've suggested? Do you need additioanl help on it?
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
 
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you. You must tell the participants why you wish to do this, and allow for Expert response.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question. Again, please comment to advise the other participants why you wish to do this.

For special handling needs, please post a zero point question in the link below and include the question QID/link(s) that it regards.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Please click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues, to track all your open and locked questions at this site.  If you are an EE Pro user, use the Power Search option to find them.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.11824738.html
http://www.experts-exchange.com/questions/Q.20128291.html
http://www.experts-exchange.com/questions/Q.20185880.html
http://www.experts-exchange.com/questions/Q.20189388.html
http://www.experts-exchange.com/questions/Q.20194393.html
http://www.experts-exchange.com/questions/Q.20252160.html
http://www.experts-exchange.com/questions/Q.20252063.html
http://www.experts-exchange.com/questions/Q.20253005.html
http://www.experts-exchange.com/questions/Q.20253391.html
http://www.experts-exchange.com/questions/Q.20274164.html
http://www.experts-exchange.com/questions/Q.20264524.html

PLEASE DO NOT AWARD THE POINTS TO ME.  
 
------------>  EXPERTS:  Please leave any comments regarding your closing recommendations if this item remains inactive another seven (7) days.  Also, if you are interested in the cleanup effort, please click this link http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643

Moderators will return to this question in 7 days and close this item if still open by either moving it to the PAQ at zero points, deleting it or awarding expert(s), if expert recommendations are posted or the moderators can make that determination without expert input.
 
Thank you everyone.
 
Moondancer
Moderator @ Experts Exchange

P.S.  For any year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.

Author

Commented:
sorry for the replied, I've forgotten this question!! anyway, thanx man

Explore More ContentExplore courses, solutions, and other research materials related to this topic.