Java Modifiers

🔹 Java Modifiers

Modifiers in Java are keywords that change the behavior of classes, methods, and variables. They define access level, scope, and other properties.

There are two main types:

  1. Access Modifiers – Control visibility.

  2. Non-Access Modifiers – Provide other properties like final, static, etc.


1. Access Modifiers

Modifier Class Package Subclass World
public
protected
default (no modifier)
private
  • public → Accessible everywhere.

  • protected → Accessible in same package & subclasses.

  • default → Accessible only within same package.

  • private → Accessible only within the class.

Example: Access Modifiers for Variables

class Demo {
public int pub = 10;
protected int prot = 20;
int def = 30; // default
private int priv = 40;
void display() {
System.out.println(pub + ” “ + prot + ” “ + def + ” “ + priv);
}
}


2. Non-Access Modifiers

Modifier Description
final Cannot be changed (variable), cannot be overridden (method), cannot be inherited (class)
static Belongs to class rather than object
abstract Must be implemented in subclass (for classes and methods)
synchronized Used for thread safety in methods
volatile Variable value can be changed by multiple threads
transient Variable not serialized
native Method implemented in native code (C/C++)

Examples

a) final Variable

class Circle {
final double PI = 3.14159; // constant
void display() {
System.out.println(PI);
}
}

b) static Variable

class Counter {
static int count = 0;
Counter() { count++; }
}

public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(“Count: “ + Counter.count);
}
}

c) abstract Class

abstract class Shape {
abstract void draw(); // must be implemented in subclass
}
class Circle extends Shape {
void draw() { System.out.println(“Drawing Circle”); }
}


3. Key Points

  • Access modifiers control visibility.

  • Non-access modifiers control behavior, inheritance, and memory.

  • Modifiers can be combined (e.g., public static final int MAX = 100;).

  • Always choose modifiers for encapsulation, security, and clarity.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *