Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I have two packages in my project: odp.proj and odp.proj.test. There are certain methods that I want to be visible only to the classes in these two packages. How can I do this?

If there is no concept of a subpackage in Java, is there any way around this? I have certain methods that I want to be available only to testers and other members of that package. Should I just throw everything into the same package? Use extensive reflection?

1 Answer

0 votes
by (46k points)

The names of your packages hint that the application here is for unit testing. The typical pattern used is to put the classes you wish to test and the unit test code in the same package (in your case odp.proj) but in different source trees. So you would put your classes in src/odp/proj and your test code in test/odp/proj.

Java does have the "package" access modifier which is the default access modifier when none is specified (ie. you don't specify public, private or protected). With the "package" access modifier, only classes in odp.proj will have access to the methods. But keep in mind that in Java, the access modifiers cannot be relied upon to enforce access rules because with reflection, any access is possible. Access modifiers are merely suggestive (unless a restrictive security manager is present).

Related questions

0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...