Thursday, 9 May 2019

access modifiers in Java







Edited to fix being marked as duplicate or to be more clear on why it appears to be a duplicate. At the time I did not know that package and default where the same thus reason for this post.






now I going through exam questions in preparation for my Java exam and I have a question asking me to explain access modifiers and its asking me about a Package modifier.



I can find info on private, Protected, public and default but can't find anything on Package.




can someone please give me an answer or link me to an article about it?


Answer



package-private is not a real modifier. You can't type package-private and get the system to recognize it as an access modifier. It's really the default, made by not including any other modifiers.



It means that the given members can only be accessed in the same package.



For example, com.hexafraction.Cow can access a member with default modifiers(none actually) in com.hexafraction.Dog, but com.foo.Crow can't access that member as it's not in the same pacakge.



In this example, the following makes up Cow:




pacakge com.hexafraction;
class Cow{
void moo(){ //no public, protected, or private modifier
System.out.println("moo!");
}
}


Edit for the future: In Java 8, package will supposedly be the modifier needed for this. Literally typing default will still not apply here.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...