Access Modifiers in java
Access Modifiers in
java
Java provides a number of access modifiers to set
access levels for classes, variables, methods, and constructors. The
access modifiers in java specify accessibility (scope) of a data member,
method, constructor or class.
Example 1:- Providing access
Suppose you have a method to add two numbers. Anyone
wants to use this method if it is already written. So this should be visible
and available for everyone's use.
Example 2:- Restricting access
You have bank account class and in that you
have balance as instance variable. Now in this case it is okay for everyone to
see balance of your bank account. But it is really not okay that someone can
modify your account balance.
So here you need to restrict everyone from modifying your account balance except bank.
Access Modifiers Types
The basic Accessibility Modifiers are of
4 types in Java. They are
1.
public
2.
protected
3.
package/default
4.
private
There are other Modifiers in Java. They
are
1.
static
2.
abstract
3.
final
4.
synchronized
5.
transient
6.
native
7.
volatile
Note: A class cannot be private or protected except nested class.
If you make any class constructor private, you
cannot create the instance of that class from outside the class.
You must remember one thing; all 4 types are applicable
to class members. But only public and default access can be given to a class.
This means that a class cannot be private or protected. This will give you
compile time error.
Access Modifiers are used at 3 access levels in Java. They are
1.
Top-level for Classes
& Interfaces
2.
Member-level for
Classes & Interfaces
3.
Accessibility
Modifiers for Nested Classes & Interfaces
1) Access Modifiers for Top-level Classes & Interfaces
Only 2 basic access modifiers are applicable for Top-level
Classes & Interfaces. They are Public and Package/Default modifiers.
·
Public: If top level class or interface
within a package is declared as Public, then it is accessible both inside and
outside of the package.
·
Default: If no access modifier is specified in
the declaration of the top level class or interface, then it is accessible only
within package level. It is not accessible in other packages or sub packages.
2) Accessibility Modifiers for Members
- Public Members: If members are declared as public inside a class then such members are accessible to the classes which are inside and outside of the package where this class is visible. This is the least restrictive of all the accessibility modifiers.
- Protected Members: If members are declared as protected then these are accessible to all classes in the package and to all subclasses of its class in any package where this class is visible.
- Default Members: When no accessibility modifier is specified for the member then implicitly it is declared as Default. These are accessible only to the other classes in the class’s package.
- Private Members: This is the most restrictive of all accessibility modifiers. These members are accessible only with in the same class. These are not accessible from any other class within a class’s package also.
Public Access
When a class member is declared public then all
other classes can access that member, regardless of the package that class
belong to. This also assumes that class should also be visible.
Example :-
public class MyMath {
public int add(int a, int b)
{
int c = a + b;
int c = a + b;
return c;
}
}
Now any class can access this add method simply by making object of MyMath like
MyMath m1 = new MyMath ();
m1.add(5, 3);
Private Access
Class members which are
marked private cannot be accessed outside of that class.
Private class members will
also not be visible by inheritance.
They are exclusive to that class only.
Example:-
public class MyMath {
private int add(int a, int
b){
int c = a + b;
return c;
}
public static void
main(String args[]){
int result = new MyMath().add(3,5);
System.out.println(result);
}
}
Here add method can only
be accessed by MyMath and cannot be accessed beyond this by any means like
object. But you can access it by other public method of same class.
Protected Access
Protected members can be
accessed (through Inheritance) by
sub class even if sub class belongs to different package.
Example:-
//save by A.java
package com.mypack.test;
public class MyMath {
protected int add(int a,
int b){
int c = a + b;
return c;
}
}
Another Class
//save by B.java
package com.yourpack.test;
public class YourMath extends MyMath {
public void check() {
int ans = add(3,4);
System.out.println(ans);
}
}
Output: 7
class YourMath can access
protected method inside MyMath even if they belong to different packages.
Default Access
Default members can be
accessed only if the class accessing the member belongs to the same package.
Example:-
package com.mypack.test;
public class MyMath {
int add(int a, int b){
int c = a + b;
return c;
}
}
Another Class
package com.mypack.test;
public class YourMathClass {
public void testIt() {
int result = add(2,4);
System.out.println(result);
}
}
Here add method has
default access and it can be accessible by other classes in same package.
Let's understand the access
modifiers by a simple table.
Access Modifier
|
within class
|
within package
|
outside package by
subclass only
|
outside package
|
Private
|
Y
|
N
|
N
|
N
|
Default
|
Y
|
Y
|
N
|
N
|
Protected
|
Y
|
Y
|
Y
|
N
|
Public
|
Y
|
Y
|
Y
|
Y
|
Static Members:
·
Static members are the
members with Static keyword in their declarations.
·
Class variables are
called as Static variables. These members belong to the class not to the object
i.e. they are not instantiated when the class instance is created.
·
The values of these
variables are not part of the object state.
·
The static variables
are initialized to their default values (if explicit initialization is not
specified) at the time of class loading.
·
The Static methods are
called as class methods. A static method can directly access other static
members in the class. It cannot access instance (non-static) members of the
class. But it can always use a reference of the class type to access its
members both static and non-static.
Final Members:
·
Final variable is a
constant; its value cannot be changed after its initialization.
·
This applies to
instance, static and local variables including parameters that are declared as
final.
·
A final variable of
primitive data type cannot change its value once it has been initialized. A
final variable of a reference type cannot change its reference value once it
has been initialized, but the state of the object it denotes can still be
changed.
Note:
·
Variables defined in
Interfaces are implicitly Final.
·
Final variables must
be initialized before it is used.
·
Final methods in a
class are complete i.e. these methods has implementations and hence cannot be
overridden in the subclasses.
Abstract Methods:
If method has a keyword abstract in its
declaration, then such method/function is called Abstract method. Abstract
methods does not have an implementation i.e. method body is not defined; only
method prototype is specified in the class definition.
Note:
·
Only instance methods
can be declared as abstract.
·
Since Static methods
cannot be overridden declaring abstract static method would of no use.
·
A Final method cannot
be abstract and vice versa.
·
Methods specified in
an Interface are implicitly abstract.
Synchronized Methods:
Multiple threads can be executing in a program and at times they
might try to execute several methods on the same object simultaneously.
If there is a requirement that only one thread at a time should
execute a method in the object, then such methods can be declared as Synchronized.
Their execution will be mutually exclusive among all threads. At any given
time, at the most one thread will be executing a Synchronized method on an
object.
Note: Synchronized
methods are also applicable to Static methods of a class.
Native Methods:
Native Methods are also called as foreign methods. Such methods
implementation is not defined in Java but in another programming language.
These methods are specified in the class as method prototypes
with prefix with keyword native, no method body is defined in the Java class.
Transient Fields:
Objects can be stored using serialization. Serialization
transforms objects into an output format which is helpful for storing objects.
Objects can later be retrieved in the same state as when they were serialized,
meaning that fields included in the serialization will have the same values at
the time of serialization. Such objects are said to be Persistent.
The fields are declared with keyword Transient in their class
declaration if its value should not be saved when objects of the class are
written to persistent storage.
Volatile Fields:
During execution, complied code might cache the values of fields
for efficiency reasons. And as multiple threads will access the same field,
caching is not allowed to cause inconsistencies when reading and writing the
value in the field.
The Volatile modifier can be used to inform the
compiler that it should not attempt to perform optimizations on the field which
could cause unpredicted results when the field is accessed by multiple threads
3) Accessibility Modifiers for Nested Classes &
Interfaces
Nested Interfaces:
Access modifiers can be used in Nested interfaces. An interface
declared within another class or interface is called a Nested interface. A
top-level interface is the one which is not nested.
Only one type of nested interface is available in Java based on
declarative context, Static member interface. These are interfaces defined with
keyword Static inside the top-level interface or class or in another Static
member class or interface. It can be instantiated like a normal top-level
interface or class, no enclosing instance is required for this interface
instantiation.
Nested Classes:
Access modifiers are also used in Nested classes. A class
declared within another class is called a Nested class. A top-level class is
the one which is not nested.
They are 2 categories of Nested classes based on the declarative
context. They are
·
Static member classes
·
Inner classes
Inner classes are defined in 3 different categories. They are
·
Non-static member
classes
·
Local classes
·
Anonymous classes
Static member classes:
Classes which are defined with Static modifier inside the
top-level class or other Static member class are called Static member classes.
It can be instantiated like a normal top-level class; no enclosing instance is
required for this class instantiation.
All the 4 accessibility modifiers i.e. Public, Protected,
Package & Private are applicable to Static member classes’ declaration.
Non-Static member classes:
Classes which are defined without Static modifier inside another
class are called non-static member classes. An instance of a non-static member
class always has an enclosing instance associated with it.
The accessibility modifiers i.e. Public, Protected, Package
& Private, abstract, final are applicable to Non-Static member
classes’ declaration.
Local classes:
These classes are defined in the context of a block as in a body
of the method or normal local block, just as local variables defined in a
method body or local block. An instance of a local class has an enclosing
instance associated with it, if it is declared in non-static context.
No accessibility modifiers are applicable for Local classes.
Anonymous classes:
These are defined as expressions and instantiated on the fly. An
instance of anonymous class has an enclosing instance associated with it, if it
is declared in non-static context.
No accessibility modifiers are applicable for Anonymous classes.
Note: A Nested Class or Interface cannot have the same name as
any of the enclosing classes or interfaces.
The following rules for inherited methods:
- Methods declared public in a superclass also must be public in all subclasses.
- Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
- Methods declared private are not inherited at all, so there is no rule for them.
Comments
Post a Comment