Restricting access to an object in the same package.
Landon Blake
Ranch Hand
Joined: Dec 04, 2003
Posts: 121
posted
0
This may be totally obvioius, so please bear with me.
I've got two objects that are in the same package. I want a method in one of those objects to only be called by the second object, but no other objects in the package.
For example, I have a FairTales package that contains a Dragon class and a KnightInShiningArmor class. I only want the slayDragon() method of the Dragon class to be called by KnightInShiningArmor objects, but no other objects in the FairyTales package.
Is their an access specifier/keyword that will do this, or is there another technique that I might be missing?
Thanks a bunch.
Landon
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
This may or may not be what you're looking for. But one way to limit the public interface of a class is by referencing it through the interfaces it implements. For example:
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Edwin Dalorzo
Ranch Hand
Joined: Dec 31, 2004
Posts: 961
posted
0
May I suggest the use of nested clasess. Make the KnightInShiningArmor class a public static nested class of the Drangon class, and make private the slayDragon method of the Dragon class.
This code snippet shows how to get what you want. KnightInShiningArmor can slay a dragon, but no other class could.
For instance, King class cannot slay a dragon
But, I knight can always kill a dragon
I hope this helps!
[ May 23, 2006: Message edited by: Edwin Dalorzo ] [ May 23, 2006: Message edited by: Edwin Dalorzo ]
Adam Richards
Ranch Hand
Joined: Nov 03, 2005
Posts: 133
posted
0
Or, just put it in the same file as the other class definition, but don't make it public.
Tony Morris
Ranch Hand
Joined: Sep 24, 2003
Posts: 1608
posted
0
Originally posted by Landon Blake: This may be totally obvioius, so please bear with me.
I've got two objects that are in the same package. I want a method in one of those objects to only be called by the second object, but no other objects in the package.
For example, I have a FairTales package that contains a Dragon class and a KnightInShiningArmor class. I only want the slayDragon() method of the Dragon class to be called by KnightInShiningArmor objects, but no other objects in the FairyTales package.
Is their an access specifier/keyword that will do this, or is there another technique that I might be missing?
Thanks a bunch.
Landon
Yes, declare a private nested interface. You're touching on one of the little known realities that private methods (in Java) violate encapsulation. I can give you examples in open source projects if you like.