The members of the class can be provided access by using the access specifiers. The
Access Modifiers defines the visibility level of the members. Java provides 4 access specifiers.
1)
private:
- The private access sets visibility up to the class level.
- The private member of a class should be used within the class where it is declared.
- The private members can't be referred outside the class and the package.
The following is an example for the private access modifier.
[java]
class A{
private int info=10;
private void msg(){System.out.println("Welcome to splessons");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.info);//Compile Time Error
obj.msg();//Compile Time Error
}
}
[/java]
In the above example, two classes A and Simple are created.
A class will have private data member as well as private method. Here user is accessing these private members from outside the class that's why compile time error will be raised.
2)
default:
- The default access specifiers sets visibility level up to package level.
- Any class of a package can access the default member.
- The default members of a class cannot be referred from outside the package.
The following is an example for the default.
[java] //save by A.java
package splesson1;
class A{
void msg(){System.out.println("Welcome to splessons");}
} [/java]
[java] //save by B.java
package splesson2;
import splesson1.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
} [/java]
In the above example, class A and method msg() scope is default that is the reason it can't be accessed from outside the package.
3)
protected:
- The protected members has a visibility up to package,but it can be referred from outside the package only through inheritance.
- Once a protected member is inherited to subclass it behaves like a private in the subclass.
The following is an example for the protected.
[java] //save by A.java
package splesson1;
public class A{
protected void msg(){
System.out.println("Welcome to splessons");}
} [/java]
[java] //save by B.java
package splesson2;
import splesson1.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
} [/java]
Output:
[java]Welcome to splessons[/java]
In the above example, The A class is public so it can be accessed from outside the package. Where as msg method is declared as protected that's why it can be accessed from outside the class only by using inheritance.
4)
public:
- The public members can be referred from anywhere.
- If wanted to access public members of a class from outside the package,the class must be public.
A class can refer another class present in different package by using fully qualified class name. Any class referred with package name and the class name is known as
fully qualified class name. Import statement can also be used to import the members of a class from other package.