Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are variables without public, private or protected declared as?

Tags:

java

If instead of:

private JButton theButton; 

I define a field like this:

JButton theButton; 

What is the difference?

like image 290
jmasterx Avatar asked Nov 19 '11 00:11

jmasterx


People also ask

What happens if you don't specify public or private in Java?

In Java there are public, protected, package (default), and private visibilities; ordered from most visible to the least. If you do not specify it, by default the visibility is package.

What if a class is not declared public?

Nothing. You can still use them outside of the class (not private).

How is a variable declared private?

Variables that are declared private can be accessed outside the class, if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.


1 Answers

Package. They're visible to other classes in the same package.

FWIW, I usually use my own no-op @Package annotation on these, just to make it clear that I know what I'm doing - that I didn't just forget something. Even though it's the default, package access is probably used less in high-quality code than any of the other three possibilities - with one big exception:

In some styles of unit testing, it's desirable to be able to get access to methods or fields that are normally private. One way to provide access is to set them to package access, and put the unit test class in the same package (but usually in a different "test" directory tree). Some developers think that this is bad practice - that in general, it's bad to use private (or package-for-testing) methods in tests.

like image 139
Ed Staub Avatar answered Sep 21 '22 06:09

Ed Staub