Friday, November 25, 2016

Access Modifiers in Java

In this page, we will learn about Access Modifiers in java with examples,every Java Developer must have knowledge about Access Modifiers and how to use them in software project. This topic is writing for the sake of fresher java programmers and Experienced(who does't have clear idea how to use and where to use Access Modifiers).

In java, there are mainly 4 Access Specifiers available. They are

a) public
b) private
c) protected
d) default

a) public:  
This type of members of a class are accessible every where outside the class. That means outside of the package also can read them and use them

b) private:

This type of members of a class are not accessible outside of the class.These are limited to the within the class only by the methods of that class

c) protected:

This type of members of class are accessible outside the class,but it is used withing the directory.

d) default:

if no access specifier is written by the programmer, then the java compiler uses a 'default' access specifier. These are accessible outside the class,but within the same directory. In other words, if a class is declared as default then we can access that class only in the current package. It is also known as package level access.
 
 
I hope you people would have been written some sample java programs,when you are writing any class and its members within a package should be declared as public. Then only the class and its members will be available for use outside the package.

class modifiers:

if a class is declared as a public we can access from any where.

Example:

package pack1;                                                     
public class one                                                    
{                                                                         
public void print()
{
System.out.println("print message");
}
}

package pack2;
import pack1.one;
public class two
{
public static void main(String args[])
{
one o=new one();
o.print();
}
}


Note:  if we are not declaring class 'one' as public then while compiling 'two' class we will get compile time error saying pack1.one is not public . can't be accessed from outside package.

If we are using private modifier for out top level class then we will get compile time error.



Example:

private class Demo
{
public static void main(String[] args)
{
int x=5;
if(x==5)
{
System.out.println("i am programmer");
}
else
{
System.out.println("i am hacker");
}


Output:





Demonstration of over all access modifiers as below:




No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...