Java Modifiers (Part 1)
Java Modifiers
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
- Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
- Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
- Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
- Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
Non-access Modifiers:
ModifierName Overview
static The member belongs to the class, not to objects of that class.
final Variable values can't be changed once assigned, methods can't be overriden, classes can't be inherited.
abstract If applied to a method - has to be implemented in a subclass, if applied to a class - contains abstract methods
synchronized Controls thread access to a block/method.
volatile The variable value is always read from the main memory, not from a specific threads memory.
transient The member is skipped when serializing an object.
Here we declare some private variables and try to access them by methods.
To learn about methods click here.
class
OtherClass
{
public
int
id
;
public
String
firstNam
e;
private
int
age
;
private
String
lastName
; } public class
MyClass
{ public static void main(String[] args) { OtherClass
obj
= new OtherClass();
obj
.
id
= 7685;
obj
.
firstName
= "
Bob
";
obj
.
age
=15;
//unable to access as set to private
obj
.
lastName
="
Denver
";
//unable to access as set to private
} }
We are unable to access int age and String lastName as they are set to private.
Final example:-
Final variable once declared in an program , remains throughout the program i.e does not change once declared.
public class
MyClass
{
final
int V
alueOfX
= 5;
final
double
PI
= 3.14; public static void main(String[] args) { MyClass
obj
= new MyClass();
obj.PI
= 3.15;
// generates error, cannot change once declared
obj.ValueOfX
= 6;
// generates error, cannot change once declared
} }
As abstract modifier is explained by the concept of Inheritance , I would cover that access modifier after explaining Inheritance.