SlideShare a Scribd company logo
1 of 12
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child class.
If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class,
within the package and outside the package.
Access Modifiers
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
Understanding Java Access Modifiers
What are Access Modifiers?
In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables,
methods, constructors, data members, and the setter methods. For example,
In the above example, we have declared 2 methods: method1() and method2(). Here,
method1 is public - This means it can be accessed by other classes.
method2 is private - This means it can not be accessed by other classes.
Note the keyword public and private. These are access modifiers in Java. They are also known as
visibility modifiers.
lass Animal {
public void method1()
{...}
private void method2()
{...}
}
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
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());
}
} Output:
The name is Programiz
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
Note: We cannot declare classes and interfaces private in Java. However, the nested classes can be declared
private
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();
}
} Output:
I am an animal
In the above example, we have a protected method named display() inside the Animal class. The Animal
class is inherited by the Dog class.
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();
}
}
Here,
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.
Output:
I am an animal.
I have 4 legs.
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.
Access Modifier.pptx

More Related Content

What's hot

Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in javaHrithikShinde
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vishal Patil
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdmHarshal Misalkar
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 

What's hot (20)

Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
C# Access modifiers
C# Access modifiersC# Access modifiers
C# Access modifiers
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java interface
Java interfaceJava interface
Java interface
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Class 10
Class 10Class 10
Class 10
 

Similar to Access Modifier.pptx

Access Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfAccess Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfsanjeevtandonsre
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptxMDRakibKhan3
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in javaAshwin Thadani
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesVinay Kumar
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxRudranilDas11
 
3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docx3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docxcarold12
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Power point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPsPower point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPsAdrizaBera
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packagesmanish kumar
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In JavaMD SALEEM QAISAR
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesSakkaravarthiS1
 

Similar to Access Modifier.pptx (20)

Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Access Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfAccess Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdf
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docx3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docx
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Power point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPsPower point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPs
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 

Access Modifier.pptx

  • 1. The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. There are four types of Java access modifiers: Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. Access Modifiers There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. There are two types of modifiers in Java: access modifiers and non-access modifiers.
  • 3. What are Access Modifiers? In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and the setter methods. For example, In the above example, we have declared 2 methods: method1() and method2(). Here, method1 is public - This means it can be accessed by other classes. method2 is private - This means it can not be accessed by other classes. Note the keyword public and private. These are access modifiers in Java. They are also known as visibility modifiers. lass Animal { public void method1() {...} private void method2() {...} }
  • 4. 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
  • 5. 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";
  • 6. 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()); } } Output: The name is Programiz
  • 7. 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 Note: We cannot declare classes and interfaces private in Java. However, the nested classes can be declared private
  • 8. 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(); } } Output: I am an animal
  • 9. In the above example, we have a protected method named display() inside the Animal class. The Animal class is inherited by the Dog class. 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.
  • 10. 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(); } } Here, 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. Output: I am an animal. I have 4 legs.
  • 11. 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.