Java Non-Access Modifiers: Usage and Examples
Table of Content:
Access modifiers in Java helps to restrict the scope of a class, constructor , variable , method or data member.
There are two types of modifiers in java:
- Access control modifier
- Non Access Modifier
1) Access control modifier
There are three access modifiers. Not including default access modifier . Default is an access control which will be set when one does not specify any access modifier.
-
Java language has four access modifier to control access levels for classes, variable methods, and constructor.
- Default: Default has scope only inside the same package
- Public: Public has scope that is visible everywhere
- Protected: Protected has scope within the package and all sub classes
- Private: Private has scope only within the classes
2) Non-access Modifier
Non-access modifiers do not change the accessibility of variables and methods, but they do provide them special properties. Non-access modifiers are of 5 types,
- Final
- Static
- Transient
- Synchronized
- Volatile
Final
Final modifier is used to declare a field as final i.e. it prevents its content from being modified. The final field must be initialized when it is declared. Final keyword can be used with a variable, a method or a class.
- Final Variable
When a variable is declared as final, then its value cannot be changed. The variable acts like a constant.
Syntax: final int a = 5;
- Final Method
When a method is declared as final, then that method cannot be overridden.
Example:
class ClassA{ final void learn(){ System.out.println("learning something new"); } } class Student extends ClassA{ void learn(){System.out.println("learning something interesting");} public static void main(String args[]){ Student object= new Student(); object.learn(); } }
This will give a compile time error because the method is declared as final and thus, it cannot be overridden.
Note: A final method can be inherited/used in the subclass, but it cannot be overridden.
Example :
class Cloth { final int MAX_PRICE = 1299; //final variable final int MIN_PRICE = 419; final void display() //final method { System.out.println("Maxprice is" + MAX_PRICE ); System.out.println("Minprice is" + MIN_PRICE); } }
A class can also be declared as final. A class declared as final cannot be inherited. String class in java.lang package is an example of final class. A method declared as final can be inherited but you cannot override(redefine) it.
Learn more about final keywordStatic Modifier
Static Modifiers are used to create class variable and class methods which can be accessed without an instance of a class. Let's study how it works with variables and member functions.
Static with Variables
Static variables are defined as a class member that can be accessed without any object of that class. A static variable has only one single storage. All the object of the class having static variable will have the same instance of the static variable. Static variables are initialized only once.
A static variable is used to represent a common property of a class. It saves memory. Suppose there is 100 employee in a company. All employee has its unique name and employee id but company name will be same all 100 employees. Here company name is the common property. So if you create a class to store employee detail, company_name field will be marked as static.
Example
class Employee { int e_id; String name; static String company_name = "atnyla"; }
Example of static variable
class Employee { int eid; String name; static String company_name ="atnyla"; public void show() { System.out.println(eid+" "+name+" "+company_name); } public static void main( String[] args ) { Employee se1 = new Employee(); se1.eid = 104; se1.name = "Ramboo"; se1.show(); Employee se2 = new Employee(); se2.eid = 108; se2.name = "Rahul"; se2.show(); } }
Output :
104 Ramboo atnyla 108 Rahul atnyla
Static variable vs Instance Variable
Static variable | Instance Variable |
---|---|
Represent common property | Represent unique property |
Accessed using class name | Accessed using object |
get memory only once | get new memory each time a new object is created |
Example
public class Test1 { static int x = 100; int y = 100; public void increment() { x++; y++; } public static void main( String[] args ) { Test1 t1 = new Test1(); Test1 t2 = new Test1(); t1.increment(); t2.increment(); System.out.println(t2.y); System.out.println(Test1.x); //accessed without any instance of class. } }
Output :
101 102
See the difference in the value of two variable. Static variable x shows the changes made to it by increment() method on the different object. While instance variable y show only the change made to it by increment() method on that particular instance.
Static Method
A method can also be declared as static. Static methods do not need an instance of its class for being accessed. the main() method is the most common example of the static method. the main() method is declared as static because it is called before any object of the class is created.
Example :
class Test1 { public static void square(int x) { System.out.println(x*x); } public static void main (String[] arg) { square(8) //static method square () is called without any instance of class. } }
Output: 64
Static block
Static block is used to initialize static data member. Static block executes before main()
method.
Example
class Employee { int eid; String name; static String company_name; static { company_name ="atnyla"; //static block invoked before main() method } public void show() { System.out.println(eid+" "+name+" "+company_name); } public static void main( String[] args ) { Employee se1 = new Employee(); se1.eid = 104; se1.name = "Ramboo"; se1.show(); } }
Output :
104 Ramboo atnylaLearn more about
static
keyword
Q. Why a non-static variable cannot be referenced from a static context?
When you try to access a non-static variable from a static context like the main method, java compiler throws a message like "a non-static variable cannot be referenced from a static context". This is because non-static variables are related with an instance of the class(object) and they get created when an instance of a class is created by using the new operator. So if you try to access a non-static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and associated with it.
Example of accessing non-static variable from a static context
class Test1 { int x; public static void main(String[] args) { x=10; } }
Output :
compiler error: non-static variable count cannot be referenced from a static context
Same example using instance of class
class Test1
{
int x;
public static void main(String[] args)
{
Test1 tt=new Test1();
tt.x=10; //works fine with instance of class
}
}
Q. Why main() method is static in java?
Because static methods can be called without any instance of a class and main() is called before any instance of a class is created.
class Simple{ // This is my first java program. public static void main(String args[]){ System.out.println("Inside main() method, which is static"); } }
Transient modifier
When an instance variable is declared as transient, then its value doesn't persist when an object is serialized
Synchronized modifier
When a method is synchronized it can be accessed by only one thread at a time. We will discuss it in detail in Thread.
Volatile modifier
Volatile modifier tells the compiler that the volatile variable can be changed unexpectedly by other parts of your program. Volatile variables are used in case of multithreading program. volatile keyword cannot be used with a method or a class. It can be only used with a variable.