Controlling Access to Members of a Class
Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:
- At the top level public , or package-private (no explicit modifier).
- At the member level public , private , protected , or package-private (no explicit modifier).
A class may be declared with the modifier public , in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes you will learn about them in a later lesson.)
At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected . 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.
The following table shows the access to members permitted by each modifier.
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |
The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member. The fourth column indicates whether all classes have access to the member.
Access levels affect you in two ways. First, when you use classes that come from another source, such as the classes in the Java platform, access levels determine which members of those classes your own classes can use. Second, when you write a class, you need to decide what access level every member variable and every method in your class should have.
Let’s look at a collection of classes and see how access levels affect visibility. The following figure shows the four classes in this example and how they are related.
Classes and Packages of the Example Used to Illustrate Access Levels
The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.
Modifier | Alpha | Beta | Alphasub | Gamma |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |
If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.
- Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
- Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.
Access Modifiers in Java
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this tutorial, we’re going over access modifiers in Java, which are used for setting the access level to classes, variables, methods, and constructors.
Simply put, there are four access modifiers: public, private, protected and default (no keyword).
Before we begin let’s note that a top-level class can use public or default access modifiers only. At the member level, we can use all four.
2. Default
When we don’t use any keyword explicitly, Java will set a default access to a given class, method or property. The default access modifier is also called package-private, which means that all members are visible within the same package but aren’t accessible from other packages:
package com.baeldung.accessmodifiers; public class SuperPublic < static void defaultMethod() < . >>
defaultMethod() is accessible in another class of the same package:
package com.baeldung.accessmodifiers; public class Public < public Public() < SuperPublic.defaultMethod(); // Available in the same package. >>
However, it’s not available in other packages.
3. Public
If we add the public keyword to a class, method or property then we’re making it available to the whole world, i.e. all other classes in all packages will be able to use it. This is the least restrictive access modifier:
package com.baeldung.accessmodifiers; public class SuperPublic < public static void publicMethod() < . >>
publicMethod() is available in another package:
package com.baeldung.accessmodifiers.another; import com.baeldung.accessmodifiers.SuperPublic; public class AnotherPublic < public AnotherPublic() < SuperPublic.publicMethod(); // Available everywhere. Let's note different package. >>
For more details on how the public keyword behaves when applied to a class, interface, nested public class or interface and method, see the dedicated article.
4. Private
Any method, property or constructor with the private keyword is accessible from the same class only. This is the most restrictive access modifier and is core to the concept of encapsulation. All data will be hidden from the outside world:
package com.baeldung.accessmodifiers; public class SuperPublic < static private void privateMethod() < . >private void anotherPrivateMethod() < privateMethod(); // available in the same class only. >>
This more detailed article will show how the private keyword behaves when applied to a field, constructor, method and to an inner class.
5. Protected
Between public and private access levels, there’s the protected access modifier.
If we declare a method, property or constructor with the protected keyword, we can access the member from the same package (as with package-private access level) and in addition from all subclasses of its class, even if they lie in other packages:
package com.baeldung.accessmodifiers; public class SuperPublic < static protected void protectedMethod() < . >>
protectedMethod() is available in subclasses (regardless of the package):
package com.baeldung.accessmodifiers.another; import com.baeldung.accessmodifiers.SuperPublic; public class AnotherSubClass extends SuperPublic < public AnotherSubClass() < SuperPublic.protectedMethod(); // Available in subclass. Let's note different package. >>
The dedicated article describes more about the keyword when used in a field, method, constructor, inner class and the accessibility in the same package or a different package.
6. Comparison
The table below summarises the available access modifiers. We can see that a class, regardless of the access modifiers used, always has access to its members:
7. Conclusion
In this short article, we went over access modifiers in Java.
It’s good practice to use the most restrictive access level possible for any given member to prevent misuse. We should always use the private access modifier unless there is a good reason not to.
Public access level should only be used if a member is part of an API.
As always, the code examples are available over on Github.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: