access modifiers in java
access modifiers in java :: futureX |
There are 4 types of access modifiers:
- private
- default
- protected
- public
Private :
The private access modifier is accessible only within class.
example :
class Emp{private int id;
private void show(){System.out.println(id);}
}
class Test{
public static void main(String args[]){
Emp e=new Emp();
e.id=10;
e.show();
}
}
output:compile time error
Note: A class cannot be private or protected except nested class.
Default :
If you don't use any modifier, it is treated as default modifier by default. The default modifier is accessible only within package.
example:
//save as A.java
package com.futurex;
public class A{
void msg(){System.out.println("hello");}
}
//save as Test.java
package com.techshakti;
import com.futurex.*;
class Test{
public static void main(String args[]){
A a=new A();
a.msg();
}
}
output: msg() is not public in A; cannot be accessed from outside package
Protected :
The protected access modifier is accessible within package and outside the package by only through inheritance.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
example:
package com.futurex;
public class A{
protected void msg(){System.out.println("hello");}
}
//save as Test.java
package com.techshakti;
import com.futurex.*;
class Test extends A{
public static void main(String args[]){
Test t=new Test();
t.msg();
}
}
Public:
The public access modifier is accessible everywhere. It has the widest scope among all other modiers.
example:
//save as A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save as B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
JAVA TUTORIALS HOMEPAGE
0 comments: