Professional Documents
Culture Documents
WEEK 11:
Non-Access Modifiers in Java
Learning Objectives:
To use the different access modifiers in Java.
To distinguish between access modifier and
non-access modifier.
Access and Non-Access Modifiers in Java
In Java, a modifier has a reserved keyword that is included in the
definition of class, method, and variables. A modifier adds some
meanings to these definitions. Modifiers are also called specifiers.
Static Modifier
Final Modifier
Abstract Modifier
Synchronized Modifier
Transient Modifier
Volatile Modifier
Static Modifier
Static Modifier is used for creating a static variable and
static method. The reserved keyword for a static modifier is
static, which is used before the data type of the variable or
method.
A static method or variable exists independently of any
Test.java OUTPUT:
public class Test{ //initialization of class A new car has been created
public static void main(String[] args){
//value is stored in static variable
Car.msg = "A new car has been created"; In the Test.java class, we initialized the
// static method in class Car is invoked static variable msg in the Car class
Car.create(); and invoked create() method in
class Main defined in the Car class without
} creating any object of class Car,
} //end of class
Final Modifier
In Java, variable, method, and class can have a final non-
access modifier. The reserved keyword for a final non-
access modifier is final. This keyword is used to make any
class, method, or variable final.
Once a final variable is initialized, you cannot change its
value again.
Test2.java 1ST OUTPUT:
public class Test2{ //initialization of class Test2.java:9: error: cannot assign a value to
final variable number
number = 2; //change value of
//declare a final variable of int data type number
public final int number = 1;
COMPILE TIME ERROR DUE TO
//non-static method to print number value REASSIGNING VALUE TO FINAL
public void print(){ VARIABLE.
System.out.print(number); //print number
number = 2; //change value of number
System.out.print(number); //print new value
}
// main method
public static void main(String[] args){ 2ND OUTPUT:
//object of class Test2 to access non-static methods 11
Test2 t2 = new Test2();
}
}
END OF PRESENTATION…