Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Method accessibility inside package-private class?

If I have a java class which is package-private (declared with "class", not "public class"), there is really no difference if the methods inside are declared public or protected or package-private, right? So which should I use, or when should I use which? I'm a bit confused.

like image 333
mk12 Avatar asked Aug 29 '09 01:08

mk12


People also ask

Is private method accessible from inside all classes in the same package?

The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Can we access private method in Java?

We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.

Can object of a class access private methods?

Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.


2 Answers

If I have a java class which is package-private (declared with "class", not "public class"), there is really no difference if the methods inside are declared public or protected or package-private, right?

Well maybe not immediately. But if you then (or in the future) declare a 'protected' or 'public' class that inherits from the package-private class, then the visibility of the members of the original class do matter.

As @kmccoy points out, declaring the class as final removes the possibility of subclasses.

But this is really only window-dressing. If you then decide that you really need to create subclasses, you simply remove the final ... and then you are back in the situation where the choice of access modifiers does matter.

IMO, the bottom line is that you should pick the most appropriate modifiers ... even if it is not necessary right now. If nothing else, your choice of modifiers should document your intent as to where the abstraction boundaries lie.

like image 172
Stephen C Avatar answered Oct 13 '22 12:10

Stephen C


Public methods inside a package class are public to classes in the same package. But, private methods will not be accessible by classes in the same package.

like image 25
Jeremy Powell Avatar answered Oct 13 '22 10:10

Jeremy Powell