Java default property access

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

Источник

What are Access Modifiers?

Access Modifiers in Java Explained

Access Modifiers in Java Explained

Have you ever wanted to define how people would access some of your properties? You would not want anyone using your underwear. However, your close friends and relatives can use your sweater and maybe your car.

Similarly to how you set a level of access to your posessions, Java controls access, too. You want to define the access level for variables, methods and classes depending on which other classes you want accessing them.

Java provides 4 levels of access modifiers. This means that you can modify access to a variable, method or a class in 4 ways. These 4 ways are private, public, protected and default.

These access modifiers can be applied to fields, methods and classes (Classes are a special case, we will look at them at the end of this artice). Here is a quick overview 1 of what the Access Levels are for each Access Modifier :

Access Modifiers Table Reference:

Access Modifiers Table

Private Access Modifier

Allows a variable or method to only be accessed in the class in which it was created. No other class beyond the class that created the variable or method can access it. This is closely similar to your internal organs. They are only accessible to the owner. To make a variable or method private, you simply append the private keyword before the variable or method type. Let us use private in a coding example. If a bank wants to provide an interest rate of 10% on it’s loans, it would make sure that the interest rate variable(let us suppose int int_rate; ) would stay private so as no other class would try to access it and change it. For example;

private String name;
The above example creates a variable called name and ensures that it is only accessible within the class from which it was created.

Another example for a method is

The above example ensures that the method setAge is accessible only within the class from which it was created and nowhere else.

Public Access Modifier

The public access modifier is the direct opposite of the private access modifier. A class, method or variable can be declared as public and it means that it is accessible from any class. Public access modifier can be likened to a public school where anyone can seek admission and be admitted.

A public class, method, or variable can be accessed from any other class at any time.

For example, to declare a class as public, all you need is:

As such, the Animal class can be accessed by any other class.

public int age; public int getAge()

Above are ways of specifying a variable and a method as public.

The Default Access Modifier

The default access modifier is different from all the other access modifiers in that it has no keyword. To use the default access modifier, you simply use none of the other access modifiers and that simply means you are using a default access modifier.

For example, to use the default access modifier for a class, you use

This basically means you are using the default access modifier. The default access modifier allows a variable, method, or class to be accessible by other classes within the same package. A package is a collection of related classes in a file directory. For more information about packages, check out the section on packages.

Any variable, method, or class declared to use the default access modifier cannot be accessed by any other class outside of the package from which it was declared.

Above are some ways of using the default access modifier for a variable or method. Don’t forget, the default access modifier does not have a key word. The absence of the 3 other access modifiers means you are using the default access modifier.

Protected Access Modifier

The protected access modifier is closely related to the default access modifier. The protected access modifier has the properties of the default access modifier but with a little improvement.

A variable and method are the only ones to use the protected access modifier. The little improvement is that a class outside the class package from which the variable or method was declared can access the said variable or method. This is possible ONLY if it inherits from the Class, however.

The class from another package which can see protected variables or methods must have extended the Class that created the variables or methods.

Note without the advantage of Inheritance, a default access modifier has exactly the same access as a protected access modifier.

Examples of using the protected access modifier is shown below:

protected int age; protected String getName()

Access Modifiers on Classes

By default, classes can only have 2 modifiers:

So this means classes can never be set to private or protected ?

This is logical, why would you want to make a private class? No other class would be able to use it. But sometimes, you can embed a class into another class. These special classes, inner classes , can be set to private or protected so that only its surrounding class can access it:

In the above example, only the Car class can use the Engine class. This can be useful in some cases.

Other classes can never be set to protected or private , because it makes no sense. The protected access modifier is used to make things package-private but with the option to be accessible to subclasses. There is no concept such as ‘subpackages’ or ‘package-inheritance’ in java.

Источник

Модификаторы доступа в Java

Модификаторы доступа в Java: public, private, protected, default

В этой статье мы рассмотрим модификаторы доступа в Java, которые используются для настройки уровня доступа к классам, переменным, методам и конструкторам.

Существует четыре модификатора доступа: public, private, protected и default (без ключевого слова).

Прежде чем мы начнем, давайте отметим, что класс верхнего уровня может использовать только public или default модификаторы доступа. На уровне членов классов мы можем использовать все четыре типа доступа.

Default

Когда мы явно не используем какое-либо ключевое слово, Java установит доступ по умолчанию (default) к данному классу, методу или свойству. Модификатор доступа по умолчанию также называется package-private, что означает, что все элементы видны в одном пакете, но недоступны из других пакетов:

package com.test.accessmodifiers; public class SuperClass < static void defaultMethod() < . >>

defaultMethod() доступен в другом классе того же пакета:

package com.test.accessmodifiers; public class Public < public Public() < SuperClass.defaultMethod(); // метод доступен в том же пакете >>

Однако этот метод недоступен в других пакетах.

Public

Если мы добавляем ключевое слово public к классу, методу или свойству, то мы делаем его доступным для всего мира, т.е. все остальные классы во всех пакетах смогут его использовать. Это наименее ограничивающий модификатор доступа:

package com.test.accessmodifiers; public class SuperClass < public static void publicMethod() < . >>

publicMethod() доступен в другом пакете:

package com.test.accessmodifiers.another; import com.test.accessmodifiers.SuperClass; public class AnotherClass < public AnotherClass() < SuperClass.publicMethod(); // метод доступен в любом пакете >>

Private

Любой метод, свойство или конструктор с ключевым словом private доступен только из того же класса. Это самый ограничительный модификатор доступа, лежащий в основе концепции инкапсуляции. Все данные будут скрыты от внешнего мира:

package com.test.accessmodifiers; public class SuperClass < static private void privateMethod() < . >private void anotherPrivateMethod() < privateMethod(); // доступен только в этом же классе >>

Protected

Между уровнями public и private доступа есть модификатор защищенного доступа – protected.

Если мы объявляем метод, свойство или конструктор с ключевым словом protected, мы можем получить доступ к члену из того же пакета (как и с уровнем доступа package-private) и, кроме того, из всех подклассов его класса, даже если они находятся в других пакетах:

package com.test.accessmodifiers; public class SuperClass < static protected void protectedMethod() < . >>

protectedMethod() доступен в подклассах (независимо от пакета):

package com.test.accessmodifiers.another; import com.test.accessmodifiers.SuperClass; public class AnotherSubClass extends SuperClass < public AnotherSubClass() < SuperClass.protectedMethod(); // доступен в подклассе, несмотря на другой пакет >>

В таблице ниже приведены краткие сведения о доступных модификаторах доступа. Мы можем видеть, что класс, независимо от используемых модификаторов доступа, всегда имеет доступ к своим членам:

Модификатор Класс Пакет Подкласс Полная видимость
public Да Да Да Да
protected Да Да Да Нет
default Да Да Нет Нет
private Да Нет Нет Нет

Заключение

В этой короткой статье мы рассмотрели модификаторы доступа в Java.

Хорошей практикой является использование максимально закрытого уровня доступа, чтобы предотвратить злоупотребление. Мы всегда должны использовать модификатор доступа private, если только нет веской причины не делать этого.

Источник

Читайте также:  Серые цвет html код
Оцените статью