share

Wednesday, 4 November 2015

Access and Non-Access Modifiers in java

Modifiers are
keywords that you add to those definitions to change their meanings.

There are two types
of modifiers in java: access modifiers and non-access modifiers. The access modifiers
in java specifies accessibility (scope) of a data member, method,
constructor or class.

There are 4 types of
java access modifiers:

1. private

2. default

3. protected

4. public

1. private:

private modifiers access only within class. If we try access private
modifiers outside of class ,it produce compilation error. We There is
two class user and test.User class have private variable and
methods. If we try access private data out side of class then it
gives error.

For this see public
modifiers . Public modifies explain below in this post.

2 Default
:

Default
has scope only inside the same package. If we try access default
modifiers outside of class , it gives error.

There is two
classes Demo and User in different packages.

package
com.javamodifier;

importcom.javatest.User;

publicclass
Demo {

publicstaticvoid
main(String[] args) {

User
user = new
User();

System.out.println(user.name);//
CE

}

}

package
com.javatest;

publicclass
User {

String
name
;

publicvoid
display(){

System.out.println("name
of user ="+name);

}

}

3. protected
:

Protected has scope within the package and all sub classes. In this
Example We access Student's protected method by inheritance.

package
com.javamodifier;

import
com.javatest.Student;

publicclass
Demo extendsStudent
{

publicstaticvoid
main(String[] args) {

Student student = new
Student();

student.print();

}

}

package
com.javatest;

publicclass
Student {

protectedvoidprint(){

System.out.println("
Student Called");

}

}

Output:

Studnet Called

4. Public:

Public
scope is visible everywhere. In previous examples we can access print
method of student class without inherintance ,if it declare as
public.

package
com.javamodifier;

import
com.javatest.Student;

publicclass
Demo {

publicstaticvoid
main(String[] args) {

Student student = new
Student();

student.print();

}

}

package
com.javatest;

publicclass
Student {

publicvoidprint(){

System.out.println("
Student Called");

}

}

How to Access
Private Modifiers Outside Class:

We can access
private modifiers outside class using public method of this
class(withoout using inherintance). Below we give example. Emp class
have private data mamber empId and private method diplaySalary. These
private modifiers we access throw public accessEmp() method.