Class Modifiers – Static and Final

11 months ago

In the previous section we have discussed in detail about the Access Modifiers and how each modifier helps in laying restrictions. Now we will be studying about the Non Access Modifiers, which help in determining the behavior.

This section will focus on the following two common Non-Access Modifiers

  1. Static
  2. Final

Let’s dig deeper and look into each one of them in detail:

Static Keyword

Whenever we talk about memory management, the static keyword comes into action. This keyword helps us in allocation of the memory effectively. Declaring a method, variable, block of code, etc. as static means that they belong to the class not the instance of the class.

Another important point to note, when a member is written as static then that member can be accessed, before the actual objects are created.

We can use the Static keyword in Java for the following members:

  1. Method (also called as class method)
  2. Variable (also called as class variable)
  3. Block of Code
  4. Nested Classes
  1. Java Static Methods

Declaring a method as static is called a static method or class method. Whenever a method is declared as static, then it can be accessed before any object of the class is created.

The most common usage of the static method is main() method. We do not need to create the Object of the class in order to work with the main() body.

Some important points to note about the static method are:

  • It belongs to the class rather than the object of class.
  • Static method can only access static data and change their values.
  • We can call static methods without creating the objects of the class.
  • Static methods can only call or refer other static methods.

Example-

class Test {
	int age;
	String name;
	static String universityName = "QA"; // Static variable

	// static method to change the static variable value
	static void updateUniversityName() {
		universityName = "QATechHub";
	}

	// To initialize the variable members of the class
	Test(int a, String n) {
		age = a;
		name = n;
	}

	// method to print values
	void print() {
		System.out.println(age + " " + name + " " + universityName);
	}

//Test class to create and display the values of object  

	public static void main(String args[]) {

		// creating objects
		Test obj1 = new Test(23, "Phill");
		// calling change method to update universityName
		Test.updateUniversityName();
		Test obj2 = new Test(28, "Chris");
		Test obj3 = new Test(24, "Dave");
		// calling display method
		obj1.print();
		obj2.print();
		obj3.print();
	}
}

Output-

23 Phill QATechHub
28 Chris QATechHub
24 Dave QATechHub
  1. Java Static Variables

We can create any variable as static in the class, by using the keyword static in front of it. This static variable is common for all the objects of the class. Its value is shared among all the entities of the class.

Syntax –

static int val=10;

Some important points to note about the static variables are:

  • It helps in making the memory management efficient.
  • The static variable gets memory allocated once, and can be used for all the objects.
  • The static variable values can only be changed by the static methods.

Example without static keyword

class Test {
	int age;
	String name;
	String universityName = "QA"; // Static variable

Declaration of the variable ‘unversityName’ as a Non-static variable will result in the wastage of memory space, since the variable is same throughout for all the students studying in the university. Hence, by using the above mentioned way, each Test Object will end up having a variable named as ‘universityName’, resulting in poor memory management.

However, we can avoid it by using the static keyword as shown below:

Example with static keyword

class Test {
	int age;
	String name;
	static String universityName = "QA"; // Static variable

Using the keyword static will help us to maintain a common variable ‘universityName’ between all the Test objects, which will result in efficient memory management.

  1. Block of Code

Whenever we have some line of code, that might help us initialize different members of class, then we can put that code in the static block, which will be executed as soon as the class is loaded in the memory.

Some important points to note about the static variables are:

  • Helps in initialization different members, as soon as the class is loaded in the memory.
  • This block of code will get executed exactly once.

Example –

class Test {

	static {
	System.out.println("This is the static block , which gets executed before main() method");
	}

	public static void main(String args[]) {

	System.out.println("This is not a static block, which is under main() method ");
	}
}

Output-

This is the static block , which gets executed before main() method
This is not a static block, which is under main() method 
  1. Nested Static Classes

When a class is inside another class, then they are called as Nested class. We need to use static keyword in order to make the class as static.

Some important points to note about the static Nested Classes are:

  • Only Nested classes can be declared as static.
  • Nested classes can include both static and Non-static members.

Final Non -Access Modifier

The Final keyword, can be helpful in putting various restrictions on the Data members.

We can use the Final keyword in Java for the following members:

  1. Final methods
  2. Final variable
  3. Final Class

Let’s deep dive and understand each concept:

  1. Java Final methods

Making any method of a class as a Final method means that it cannot be overridden. We can declare any method as Final by using the following line of code:

Syntax-

public final void methodName()

Some important points to note about the final java methods are:

  • Body of these methods cannot be overridden.
  • Prevents from being modified in a subclass.

Example-

class Test {
	final void display() {
		System.out.println("Parent Class Method");
	}
}

class SubClass extends Test {

	void display() {
		System.out.println("SubClass Method");
	}

	public static void main(String args[]) {
		Test obj = new Test();
		obj.display();
	}
}

Output-

Compile Time Error

We are getting a compile time error, since in the subclass we are trying to override the final display () method. And as explained above, we cannot override the final method.

  1. Java Final Variables

Whenever we declare any variable as final, then the value of that variable cannot be changed ever. A final variable, can be initialized only once in its entire life time.

Syntax-

final int value = 10;

Some important points to note about the final variables are:

  • A variable declared as Final, cannot be reassigned to a different object.
  • Final variable can be treated as constant if we use static keyword along with it.

Example-

public class Test {
	final int a = 10;

	public void changeValue() {
		a = 12; // will throw an error, since 'a' is final variable
	}
}
  1. Final Class

We can declare the class as a Final class, by using keyword Final. It prevents the class from being subclassed.

An important point to note about the Final class is:

  • A Final class cannot be inherited.

Example-

//Declaring class as Final
public final class Test { 
	final int a = 10;

	public void changeValue() {

	}
}

For further understanding the above stated differences, let us recapitulate:

BasisStaticFinal
ApplicabilityStatic keyword is applicable to all nested static classes, variables, methods and block.Final keyword is applicable only to classes, methods and variables.
InitializationIt is not necessary to initialize a static variable at the time of its declaration.It is necessary to initialize a final variable at the time of its declaration.
ModificationStatic variables can be re-initializedFinal variables cannot be re-initialized
Class
A static class’s object cannot be created and it only contains static members  
A final class cannot be inherited by any class
MethodsStatic methods are only accessible by the static members of the class, and can only be called upon by other static methodsFinal methods cannot be inherited
Block
Static block is used to initialize the static variables  
The ‘Final’ keyword supports no such block
Tejasvi Nanda

About the Author

Tejasvi Nanda