Access modifiers
There are four type of access modifier available in Java:-
- Default,
- Public,
- Private and
- Protected.
Default
In default access modifier default keyboard is not needed. When no access modifier is specified for class method or data member it is said to be default access modifier.
By default Java will accept as a public if you don't specify any access modifier.
Public
It is specified using a public keyword. To make variable or method visible to entire class , declare the variable or method as public. Example..
public int num;
public void main()
{
}
A variable or method declared as public has the widest possible visibility and accessible everywhere.
Private
Private method is specified using the keyword private. Private fields enjoy the highest degree of protection. They are accessible only with their own class.
They cannot be inherited by subclasses and therefore no accessible in subclasses.
A method declared as private behaves like a method declared as final. It prevents the method from being subclassed.
Protected
It is Specified using a protected keyword.
The protected modifier makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other other package.
Let's See all through example.
class Test
{
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i)
{
// set c's value
c = i;
}
int getc()
{
// get c's value
return c;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
Output:-
Compile Time Error.
1 Comments
nice Explained all three modifiers .... Is Java Use by default Public?
ReplyDelete