The member access rules determines whether a sub class can use a property of it's super class or it can only access or it can neither access nor access. There are two level of access control:
- At the top level: public or package-private
- At the member level: public, private, protected
At the member level, there are three different access modifiers are there: 'private', 'protected' and 'public'.
- private : If private access modifier is applied to an instance variable, method or with a constructor in side a class then they will be accessed inside that class only not out side of the class.
{
private int x=10;
}
class B extends A
{
int y=20;
System.out.println(x);//Illegal access to x ;
}
If you make any class constructor private, you can't create the instance/object of that class from outside the class. for example:
class A
{
int x;
private A(int k) // private constructor
{
x=k;
}
}
class Test
{
public static void main(String args[])
{
A ob=new A(10); //Compile time error
}
}
- protected: If protected access modifier is applied to an instance variable, method or with a constructor in side a class then they will be accessed inside the package only in which class is present and, in addition, by a sub class in another package.
- public: The class, variable, method or a constructor with public access modifier can be accessed from anywhere.
No comments:
Post a Comment