Private access modifiers in java

Java Access Modifiers

Note the keyword public and private . These are access modifiers in Java. They are also known as visibility modifiers.

Note: You cannot set the access modifier of getters methods.

Types of Access Modifier

Before you learn about types of access modifiers, make sure you know about Java Packages.

There are four access modifiers keywords in Java and they are:

Modifier Description
Default declarations are visible only within the package (package private)
Private declarations are visible within the class only
Protected declarations are visible within the package or all subclasses
Public declarations are visible everywhere

Default Access Modifier

If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default the default access modifier is considered. For example,

package defaultPackage; class Logger < void message()< System.out.println("This is a message"); >>

Here, the Logger class has the default access modifier. And the class is visible to all the classes that belong to the defaultPackage package. However, if we try to use the Logger class in another class outside of defaultPackage, we will get a compilation error.

Private Access Modifier

When variables and methods are declared private , they cannot be accessed outside of the class. For example,

class Data < // private variable private String name; >public class Main < public static void main(String[] main)< // create an object of Data Data d = new Data(); // access private variable and field from another class d.name = "Programiz"; >>

In the above example, we have declared a private variable named name . When we run the program, we will get the following error:

Main.java:18: error: name has private access in Data d.name = "Programiz"; ^

The error is generated because we are trying to access the private variable of the Data class from the Main class.

You might be wondering what if we need to access those private variables. In this case, we can use the getters and setters method. For example,

class Data < private String name; // getter method public String getName() < return this.name; >// setter method public void setName(String name) < this.name= name; >> public class Main < public static void main(String[] main)< Data d = new Data(); // access the private variable using the getter and setter d.setName("Programiz"); System.out.println(d.getName()); >>

In the above example, we have a private variable named name . In order to access the variable from the outer class, we have used methods: getName() and setName() . These methods are called getter and setter in Java.

Here, we have used the setter method ( setName() ) to assign value to the variable and the getter method ( getName() ) to access the variable.

We have used this keyword inside the setName() to refer to the variable of the class. To learn more on this keyword, visit Java this Keyword.

Note: We cannot declare classes and interfaces private in Java. However, the nested classes can be declared private. To learn more, visit Java Nested and Inner Class.

Protected Access Modifier

When methods and data members are declared protected , we can access them within the same package as well as from subclasses. For example,

class Animal < // protected method protected void display() < System.out.println("I am an animal"); >> class Dog extends Animal < public static void main(String[] args) < // create an object of Dog class Dog dog = new Dog(); // access protected method dog.display(); >>

In the above example, we have a protected method named display() inside the Animal class. The Animal class is inherited by the Dog class. To learn more about inheritance, visit Java Inheritance.

We then created an object dog of the Dog class. Using the object we tried to access the protected method of the parent class.

Since protected methods can be accessed from the child classes, we are able to access the method of Animal class from the Dog class.

Note: We cannot declare classes or interfaces protected in Java.

Public Access Modifier

When methods, variables, classes, and so on are declared public , then we can access them from anywhere. The public access modifier has no scope restriction. For example,

// Animal.java file // public class public class Animal < // public variable public int legCount; // public method public void display() < System.out.println("I am an animal."); System.out.println("I have " + legCount + " legs."); >> // Main.java public class Main < public static void main( String[] args ) < // accessing the public class Animal animal = new Animal(); // accessing the public variable animal.legCount = 4; // accessing the public method animal.display(); >>
I am an animal. I have 4 legs.
  • The public class Animal is accessed from the Main class.
  • The public variable legCount is accessed from the Main class.
  • The public method display() is accessed from the Main class.

Access Modifiers Summarized in one figure

Accessibility of all Access Modifiers in Java

Access modifiers are mainly used for encapsulation. It can help us to control what part of a program can access the members of a class. So that misuse of data can be prevented. To learn more about encapsulation, visit Java Encapsulation.

Table of Contents

Источник

Access Modifiers in Java

announcement - icon

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:

announcement - icon

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:

announcement - icon

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.

announcement - icon

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:

Источник

Java ‘private’ Access Modifier

announcement - icon

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:

announcement - icon

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:

announcement - icon

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.

Источник

Читайте также:  Java свое обработка исключений
Оцените статью