Protected access modifier in java class

Java Encapsulation & Access Modifiers Tutorial

In this Java tutorial we learn how to use access modifiers like public, private and protected to hide and protect class members.

We also discuss how to access and mutate private or protected members with getter and setter methods.

What is encapsulation

One of the three core principles in any object oriented program is encapsulation. Encapsulation is where we hide unnecessary implemetation details from the object.

As an example, consider a class that translates a document into another language.

The class would encapsulate the inner details of loading, manipulating and closing the file. We don’t need to worry about how it loads the document behind the scenes.

All we do is instantiate the class, and send it the appropriate commands, like: Open a file from this location, save file to that location etc.

Encapsulation also provides us with data protection, we can’t accidentally change how a file is manipulated from outside the class if it’s properly protected.

How to encapsulate a class with access modifiers in Java

To encapsulate members of our class, we need to use certain access modifiers. These are keywords that specify the level of access, or protection, class members have.

Читайте также:  No resource with given url found php

The table below shows the available access modifiers:

Modifier Description
public No access restriction. Can be accessed from an object or any child class
private Can only be accessed from within the class that defines it
protected Can only be accessed from within the class that defines it, as well as any child class
default Can only be accessed from within the current package

The public access modifer in Java

The public access modifier means the member can be accessed from objects, external packages and any derived classes (classes that inherit from this one).

The public modifier can be applied to classes , interfaces , methods and properties.

Источник

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.

Access Levels

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.

Visibility

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.

Источник

Protected access modifier in java class

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference 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

Источник

Оцените статью