Access Modifiers in Java
Access Modifiers in Java
com
http://www.javatpoint.com/access-modifiers
A obj=new A();
8.
System.out.println(obj.data);
9.
obj.msg();
10.
11. }
1/4
4. }
5. public class Simple{
6. public static void main(String args[]){
7.
A obj=new A();
8. }
9. }
void msg(){System.out.println("Hello");}
4. }
1. package mypack;
2. import pack.*;
3. class B{
4.
5.
6.
obj.msg();
7.
8. }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
2/4
2. public class A{
3. protected void msg(){System.out.println("Hello");}
4. }
1. package mypack;
2. import pack.*;
3. class B extends A{
4.
5.
6.
obj.msg();
7.
8. }
Output:Hello
5.
6.
obj.msg();
7.
8. }
Output:Hello
within
class
within
package
outside
package
Private
Default
Protected
Public
3/4
8.
obj.msg();
9.
10. }
The default modifier is more restrictive than protected. That is why there is compile time error.
Next TopicEncapsulation in java
prev next
4/4