Access Modifiers in Java

ACCESS MODIFIERS IN JAVA…….

An access modifier is a reserved keyword, or we can say visibility controls, which is used to restrict access. We can use these access modifiers to determine whether a field or method in a class can be called or used by another class or subclass 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, meaning within the class or outside the class. We can declare the variable in one class and use this variable in another class.

PRIVATE——

               By using a private access modifier, we cannot access that variable outside the class. We can access that data only inside the class in which we have declared it. Function, variables that are declared private are not accessed by anywhere means any other class. Private access modifier is a strict access modifier. A 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 a class or interface like the private access modifier. Methods or fields can be declared protected, but in the interface, methods and fields cannot be protected.

………..All access modifier definition is clear in the 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 ( 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;

}

}

 

Access Modifiers in Java
Access Modifiers in Java
Access Modifiers in Java

Introduction to Java