Table of Contents
Public,private and protected access modifier in Java
The access modifier in java is used to decide the accessibility of scope of a field, method and constructor or class. If you would like change the accesibility of that, you can do that by appling access modifier to it.
There are four type of Access modifiers in Java:
- Private
- Protected
- Public
- Default
We can use only public access modifiers of class in Java and not create the protected, private class.
Access modifier
Let's understand the accessibility of access modifier using a simple tableAccess modifier | Within class | Within package | Outside packages with sub class only | Outside package |
---|---|---|---|---|
Private | Y | N | N | N |
DEfault | Y | Y | N | N |
Protected | Y | Y | Y | N |
Public | Y | Y | Y | Y |
private
Program 2
At this program, variable int age and method void stu_Exam is declared private. So, we can not handle int age from another class.
When we assign variables and methods as private, the above error message is displayed.
protected
Protected Access modifier allows to access within class and its child class. Protected methods and protected variables can not be accessed from other classes .
Program 1
program 2
When we execute the above program, it produces the following results.
marks is:80
student name is mathan
Public
When we execute the above program, it produced the following results.
marks is:80
student name is kantharuban