Modifiers in Java5 min read

Introduction

Modifiers in java are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following.

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 four access levels are:

  • Default – Visible to the package, the default. No modifiers are needed.
  • Private – Visible to the class only.
  • Public – Visible to the world.
  • Protected – Visible to the package and all subclasses.

Default

If you don’t specify a modifier, it will be treated as default. The default the modifier is only available within the package. It’s not possible to get to it from outside the package. It allows for more accessibility than a private setting. It is, nevertheless, more limited than protected and open.

//save by A.java  
package package1;  
class A{  
	void msg(){
		System.out.println("Hello");
    }  
}
//save by B.java  
package package2;  
import package1.*;  
class B{  
	public static void main(String args[]){  
		A obj = new A();//Compile Time Error as class A is in different package 
		obj.msg();//Compile Time Error  
	}  
} 

Private

The private access modifier is accessible only within the class.

A simple example of private access modifier:

In this example, we have created two classes A and Simple. These classes contain private data members and private methods. We are accessing these private members from outside the class, so there is a compile-time error.

class A{  
	private int data = 15;  
	private void msg(){
		System.out.println("Hello java");
    }  
}  
  
public class Simple{  
	public static void main(String args[]){  
		A obj=new A();  
		System.out.println(obj.data);//Compile Time Error 
		obj.msg();//Compile Time Error  
	}  
}

Public

The public access modifier can be used everywhere. Among all the modifiers, it has the broadest application.

Example of public access modifier:

//save by A.java
package package1;
public class A{
	public void msg(){
		System.out.println("Hello Java");
    }
}
//save by B.java
package package2;
import package1.*;
class B{
	public static void main(String args[]){
		A obj = new A();
		obj.msg();
	}
}

Protected

  • The protected access modifier can be used both inside and outside of the package, but only through inheritance.
  • The data member, method, and function can all have the protected access modifier applied to them. It is not applicable to the class.
  • It is more accessible than the standard modifier.

Below is an example of protected access modifier:

We’ve produced two packages in this example: package1 and package2. The public A class of the package1 package can be accessed from outside the package. However, because this package’s msg function is protected, it can only be accessible from outside the class through inheritance.

//save by A.java  
package package1;  
public class A{  
	protected void msg(){
		System.out.println("Hello");
    }  
}    
//save by B.java
package package2;
import package1.*;
class B extends A{ //inheriting class A
	public static void main(String args[]){
		B obj = new B();
		obj.msg();
	}
}

Non-access Modifiers in Java

Java provides a number of non-access modifiers to achieve much other functionality.

  • Final – The final modifier for finalizing the implementations of classes, methods, and variables.
  • Static – The static modifier for creating class methods and variables
  • Abstract – The abstract modifier for creating abstract classes and methods.

Final

If you don’t want the ability to override existing attribute values, declare attributes as final. In simple words, a final variable has to be initialized when declaring and it cannot be overridden i.e. a new value cannot be assigned to a final variable.

Example:

public class Main {
	final int a = 15;
	public static void main(String[] args) {
		Main myObj = new Main();
		myObj.a = 42; // will generate an error: cannot assign a value to a final variable
	}
}

Static

static method and a static variable means that it can be accessed without creating an object of the class, unlike public.

Example:

An example to demonstrate the differences between static and public methods:

public class Main {
	// Static method
	static void myStaticMethod() {
		System.out.println("Static methods can be called without creating objects");
	}
  
	// Public method
	public void myPublicMethod() {
		System.out.println("Public methods must be called by creating objects");
	}

	// Main method
	public static void main(String[] args) {
		myStaticMethod(); // Call the static method
		myPublicMethod(); // This would output an error

		Main myObj = new Main(); // Create an object of Main
		myObj.myPublicMethod(); // Call the public method
	}
}

Abstract

The abstract modifier is applicable for only classes and methods. It is not applicable for variables. Abstraction is the process of hiding certain details and providing only the necessary information to the user.

Abstract class: An abstract class is a class that can have two types of methods: abstract and non-abstract. The child classes implementing abstract class have to implement all the abstract methods. We cannot create an object of an abstract class.

Abstract method: An abstract method is nothing but a method without a body. An abstract method can be defined in an abstract class or in an interface. The child class that is implementing an abstract class (that has an abstract method in it), has to provide the body of the abstract method.

Example:

//abstract class
abstract class Demo{
  	public void fun1(); //abstract method
	public void fun2(){ //non-abstract method
    	System.out.println("This is fun2() method");
    }
}

As the abstract class cannot be instantiated, it has to be inherited. In simple words, we have to extend the abstract class in the child class and provide the functionality to the abstract method.

//normal class
public class Child extends Demo{
	public void fun1(){
    	System.out.println("This is fun1() method"); //providing body to the abstract method
    }
  
  	public static void main(String [] args){
    	Child child = new Child();
        child.fun1();
        child.fun2();
    }
}

Output:

This is fun1() method
This is fun2() method

Share:

Leave a Reply