Contents
Access Modifiers
Public vs Protected vs Package vs Private Access Modifier in Java
Access Modifiers in Java
In Java, access modifiers are used to control the visibility and accessibility of classes, methods, and variables. By using these modifiers, we provide the JVM with information like whether a class can be accessed from outside its package, whether child classes can be created, and whether object instantiation is allowed.
Modifier 1: Public Access Modifier
When a class is declared as public
, it can be accessed from anywhere. The same applies to methods and variables declared as public within that class.
Example:
// Creating a package
package pack1;
// Declaring a public class
public class MyClass1 {
// Declaring a public method
public void display() {
System.out.println("Public Access Modifier Example");
}
}
In another package, you can import this class and use it:
// Creating a package
package pack2;
// Importing the class from pack1
import pack1.MyClass1;
public class Main {
public static void main(String[] args) {
// Creating an object of class MyClass1
MyClass1 obj = new MyClass1();
// Calling the public method
obj.display();
}
}
Output:
Public Access Modifier Example
If MyClass1
was not public, you would receive a compile-time error stating that MyClass1
is not accessible from another package.
Modifier 2: Protected Access Modifier
The protected
modifier is applicable to data members, methods, and constructors but not for top-level classes or interfaces. When a member is declared as protected
, it is accessible within the same package and in subclasses of other packages.
Example:
package pack1;
// Declaring a parent class
class MyClass2 {
// Declaring a protected method
protected void show() {
System.out.println("Protected Access Modifier Example");
}
}
Now, in another package, we can access it through inheritance:
package pack2;
// Importing the class from pack1
import pack1.MyClass2;
class ChildClass extends MyClass2 {
public static void main(String[] args) {
// Creating an instance of the child class
ChildClass obj = new ChildClass();
// Accessing the protected method
obj.show();
}
}
Output:
Protected Access Modifier Example
We can access the protected method in a subclass even from a different package, but not directly from a non-child class in another package.
Modifier 3: Private Access Modifier
The private
modifier restricts access to members within the same class only. Neither child classes nor other classes, even within the same package, can access private members.
Example:
// Defining a class
class MyClass3 {
// Declaring a private method
private void secret() {
System.out.println("Private Access Modifier Example");
}
public void accessPrivate() {
// Accessing the private method within the same class
secret();
}
}
public class Main {
public static void main(String[] args) {
MyClass3 obj = new MyClass3();
// Accessing the public method
obj.accessPrivate();
}
}
Output:
Private Access Modifier Example
Modifier 4: Default (Package) Access Modifier
When no access modifier is specified, the default access level (also called “package-private”) applies. This means that the class or its members are accessible only within the same package and not from other packages.
Example:
// Defining a class with default access
class MyClass4 {
// Declaring a default-access method
void displayMessage() {
System.out.println("Default Access Modifier Example");
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of MyClass4
MyClass4 obj = new MyClass4();
// Calling the default-access method
obj.displayMessage();
}
}
Output:
Default Access Modifier Example
Summary of Differences Between Access Modifiers
Modifier | Applicability | Accessibility From Same Package | Accessibility From Different Package | Accessibility from Subclass Outside Package | Accessibility from Non-subclass Outside Package |
---|---|---|---|---|---|
Public | Classes, Methods, Fields | Yes | Yes | Yes | Yes |
Protected | Methods, Fields | Yes | No | Yes (only in subclasses) | No |
Private | Methods, Fields | No | No | No | No |
Default (Package) | Classes, Methods, Fields | Yes | No | No | No |
Access and Non Access Modifiers in Java
Java is one of the most popular and widely-used programming languages, known for its speed, reliability, and security. Java applications can be found everywhere—from desktop software to web applications, scientific supercomputers to gaming consoles, and mobile phones to the Internet. In this guide, we’ll explore how to write a simple Java program.
Steps to Implement a Java Program
To implement a Java application, follow these key steps:
1. Creating the Program
2. Compiling the Program
3. Running the Program
If you’re looking to dive deeper into Java and gain a strong understanding of the entire development process, consider enrolling in a structured Java programming course. These courses provide hands-on experience and cover everything from basic to advanced topics, allowing you to develop efficient and scalable applications.
Example of a Simple Java Program
Here’s a basic example to illustrate the process:
// Class with multiple access modifiers
class AccessExample {
public int publicVar = 10;
private int privateVar = 20;
protected int protectedVar = 30;
int defaultVar = 40; // default access level (package-private)
// Public method
public void publicMethod() {
System.out.println("Public Method");
}
// Private method
private void privateMethod() {
System.out.println("Private Method");
}
// Protected method
protected void protectedMethod() {
System.out.println("Protected Method");
}
// Default method
void defaultMethod() {
System.out.println("Default Method");
}
}
public class MainClass {
public static void main(String[] args) {
AccessExample obj = new AccessExample();
// Accessing variables
System.out.println("Public variable: " + obj.publicVar);
System.out.println("Protected variable: " + obj.protectedVar);
System.out.println("Default variable: " + obj.defaultVar);
// Accessing methods
obj.publicMethod();
obj.protectedMethod();
obj.defaultMethod();
}
}
Output:
Public variable: 10
Protected variable: 30
Default variable: 40
Public Method
Protected Method
Default Method
The private member privateVar
and method privateMethod()
are not accessible from the MainClass
since they are declared as private
.
Non-Access Modifiers
Non-access modifiers in Java provide additional functionalities beyond access control. Java has several non-access modifiers, which can be applied to classes, methods, and variables to convey specific behavior to the JVM:
1. static: The static modifier is used to declare class-level methods and variables, meaning they belong to the class rather than to instances.
2. final: The final modifier is used to declare constants (final variables), methods that cannot be overridden, and classes that cannot be subclassed.
3. abstract: This modifier applies to classes that cannot be instantiated directly and to methods that must be implemented by subclasses.
4. synchronized: The synchronized keyword is used to control access to methods by multiple threads to ensure that only one thread executes the method at a time.
transient: This modifier is used to declare that a variable should not be serialized.
5. volatile: The volatile modifier informs the JVM that a variable’s value may change in a way that is not visible to other threads.
6. native: The native keyword indicates that a method is implemented in platform-specific code, typically in C or C++.
Example: Non-Access Modifiers
// Class with non-access modifiers
class NonAccessExample {
// Static variable
static int staticVar = 50;
// Final variable
final int finalVar = 100;
// Transient variable
transient int transientVar = 200;
// Static method
static void staticMethod() {
System.out.println("Static Method");
}
// Final method
final void finalMethod() {
System.out.println("Final Method");
}
// Synchronized method
synchronized void synchronizedMethod() {
System.out.println("Synchronized Method");
}
}
public class MainClassNonAccess {
public static void main(String[] args) {
NonAccessExample obj = new NonAccessExample();
// Accessing static members
System.out.println("Static variable: " + NonAccessExample.staticVar);
NonAccessExample.staticMethod();
// Accessing final member and method
System.out.println("Final variable: " + obj.finalVar);
obj.finalMethod();
// Calling synchronized method
obj.synchronizedMethod();
}
}
Output:
Static variable: 50
Static Method
Final variable: 100
Final Method
Synchronized Method
Key Differences Between Access and Non-Access Modifiers
- Access modifiers control the visibility and access of classes, methods, and fields.
- Non-access modifiers provide additional characteristics such as immutability, concurrency control, or indicate that something is platform-specific.