As far as I know, public/protected/private
keywords have no effect on creation time. But I wonder that keeping a public object/class accessible should have a cost. Does it have a cost?

- 48,120
- 14
- 91
- 142

- 137
- 1
- 7
-
look at http://stackoverflow.com/questions/7365329/speed-optimizing-private-and-public-variables-java, http://stackoverflow.com/questions/26676200/how-does-access-modifier-impact-the-performance-in-java, http://stackoverflow.com/questions/4279420/does-use-of-final-keyword-in-java-improve-the-performance – Andrew Tobilko Sep 29 '16 at 12:37
-
Here is an [example](http://stackoverflow.com/a/23281131/3448419) how access modifiers may affect run-time performance. – apangin Sep 29 '16 at 20:28
2 Answers
No they don't. They are essentially compile-time constructs.
That said, some OOP languages (e.g. C++) can make optimisation decisions based on something being private
. But that's unlikely to be exploitable in Java due to reflection, since in Java, being private
doesn't guarantee its invisibility to things outside the class.

- 231,907
- 34
- 361
- 483
keeping a public object/class accessible should have a cost.
Yes, the compiler needs to check whether the thing you're accessing is private, protected and public. It then decides whether you're allowed to access it.
But at runtime, the runtime doesn't need to check whether you are allowed to access the variable. Why? Because for a program to run, it must be compiled (unless you're using an interpreted language like JS). If you try to access a variable that you're not allowed to, it won't even run!
So at runtime, the runtime doesn't need to worry about whether you can access the variable, and hence, there's no effect on performance.

- 213,210
- 22
- 193
- 313
-
1This answer is not complete. At class load time - which is at runtime - the bytecode verifier checks that you're not accessing private, protected or package-private methods, fields and classes from code that doesn't have this right. This check takes some (minimal) time but only once while loading the class. – Erwin Bolwidt Sep 29 '16 at 13:05
-
-
1
-
@ahmetozkok Can't, because the question is closed as a duplicate - a poor one, because the accepted answer is copied from another question's answer but it isn't applicable because the question isn't asking about accessor methods. And neither the duplicate nor the question that the accepted answer was copied from are considering the bytecode verifier. This is very basic JVM stuff, so quite surprised that these answers are such a mess – Erwin Bolwidt Sep 29 '16 at 13:46