Access Modifiers in Java

ACCESS MODIFIERS…….

Access modifier is a reserve keyword or we can say visibility controls which is used to restrict access.We can use these access modifier to determine whether a fields or methods in a class ,can be called or used by another class or sub class or not.That means these access modifiers can prevent unauthorized updation or execution of fields and methods of the particular object.

 

 

PUBLIC -->

               BY using public you can access the data anywhere means within the class or outside the class.We can declare the variable in one class and use these variable in other class.

PRIVATE-->

               By using private access modifier we cannot access that variable outside the class.We can access that data only inside the class from which we have declare. Function,variable which are declared private is not accessed by anywhere means any other class.Private access modifier is strict access modifier.Class or interface cannot be private. Private class members can only be accessed from inside the class .

PROTECTED-->

                   The protected access modifier cannot be applied to class or interface like private access modifier.Methods or fields can be declared protected but in the interface method and fields cannot be protected.

  1. ………..All access modifier definition is clear in above example…….

class a         //base class

{

public int x; //x is the variable of public data type

private int y; //y is the variable of private means we cannot access this data type outside this class

protected int z; //z is the variable of protected data type

public void disp() //disp method is create inside the class a

{

x=5;   //value pass to variable x

y=10; //value pass to variable y

z=20; //value pass to variable z

}}

class b extends a   //derived class inherits class a

{

public void show() //method

{

a ob1;   // ob1 is the object of class a(base class)

ob1.x=101; //value given to variables

ob1.y=102; //error given because of private datatype

ob1.z=103;

}}

class first //class main

{

public static void main(String aa[]) //main static method

{

a ob1=new a(); //ob1 is the object of class a

b ob2=new b(); //ob2 is the object of class b

ob1.x=104;

ob1.y=105;   //error given because y is the private variable

ob1.z=106;

ob2.x=107;

ob2.y=108;   //error because of y variable

ob2.z=109;

}}

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @