• Embed Doc
  • Readcast
  • Collections
  • CommentGo Back
Download
 
Access Specifiers in Java
There are 3 access specifiers in Java: public, private, protected. There is a <no-access-specifier> i.e a method or class defined without any access specifier.An access specifier tells us which entity cannot be accessed from where in a program.Access modifiers can be defined at two levels, Class level and member level.
Class level
: There are two access specifiers that are valid at the class level. They arePublic and <none>. So, when we define a class, we can do it either of the ways:Public class a{}OR Class a{}If a class is defined as public, it can be accessed from outside world i.e from different packages.If a class is defined w/o any access specifier, it cannot be accessed from different packages.
Member Level
: Member level means for class variables or class methods level.Class a{<access-specifier> int var;}class a{<access-specifier> void method(){}}
 
Examples:1.Class a{ private int number1; public int number2;}2.class a{ private int number1; public int number2; private void method1(){} public void method2(){}}
Private
Access specifier : We will be seeing several examples to illustrate the usageof private access specifier.Private access specifier can be used with variables and methods in a class.
Case 1
: In case of variables, we will see what happens if a variable is declared as“Private”. We use the keyword ‘Private’ in front of the variable to declare it as a private variable.Example:Class Test{ private int number; public void Testmethod(){System.out.println(“I want to print the private variable within thisclass:”+number);
 
}} public class mainClass { public static void main(String[] args){Test t = new Test();t.Testmethod();}We have a class defined ‘Test’. That class has a private variable defined ‘number’.When a variable is declared as private, it can be accessed only from within that class.So, the variable number can only be accessed by the method Testmethod() belongingto class Test.In our main method of class mainClass, we are creating an instance of the class Test, because this is how we access instance methods.Another example to illustrate the difference between a variable declared as public Vs private.Class Test{ private int number = 4; public int number1 = 3; public void Testmethod(){System.out.println(“I want to print the private variable within thisclass:”+number);}} public class mainClass { public static void main(String[] args){Test t = new Test();System.out.println(t.number);System.out.println(t.number1);}We see a compile time error with the above program, since it is a private variable and
cannot
be accessed outside the class.
of 00

Leave a Comment

You must be to leave a comment.
Submit
Characters: ...
You must be to leave a comment.
Submit
Characters: ...