Skip to main content

Command Palette

Search for a command to run...

06.Packages & Modifiers

Published
•5 min read•View as Markdown

Perfect! Let’s move on to Packages in Java — a fundamental concept to organize classes and interfaces. I’ll explain it in full detail.


Packages in Java


1. What is a Package?

  • Definition: A package is a collection of related classes, interfaces, and sub-packages.

  • Purpose:

    1. Organize code into logical groups.

    2. Avoid naming conflicts (classes with same names).

    3. Control access using access modifiers (public, protected, etc.).

    4. Reusable and easier to maintain.


2. Types of Packages

  1. Built-in / Predefined Packages: Provided by Java SDK. Examples:

    • java.lang – automatically imported, contains fundamental classes (String, Math, Object).

    • java.util – collection framework, Date, Random.

    • java.io – file handling classes (File, BufferedReader).

    • java.sql – database connectivity.

  2. User-defined Packages: Created by developers to organize their own classes.

  3. Unnamed / Default Package: Classes written without package declaration automatically go here. Usually for small programs.


3. How to Create a User-defined Package

Step 1: Declare a package

// File: Car.java
package vehicles; // package declaration

public class Car {
    public void display() {
        System.out.println("This is a car");
    }
}

Step 2: Compile the package

javac -d . Car.java
  • -d . tells compiler to create folder structure for the package (vehicles folder).

Step 3: Use the package in another class

// File: Main.java
import vehicles.Car; // import package

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.display();
    }
}

4. Access Modifiers in Packages

ModifierVisibility / Scope
publicVisible everywhere
protectedVisible in package + subclasses
default (no modifier)Only visible in the same package
privateOnly visible inside the class

5. Advantages of Packages

  1. Code Reusability – Organize classes to reuse them in different projects.

  2. Better Maintainability – Easier to manage large projects.

  3. Namespace Management – Avoids class name conflicts.

  4. Access Control – Control which classes/members are visible outside the package.


6. Built-in Package Example

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        System.out.println(list);
    }
}

✅ Summary Table – Package Types

Package TypeDescriptionExamples
Built-in / PredefinedProvided by Java SDKjava.lang, java.util, java.io
User-definedCreated by programmerpackage vehicles;
Unnamed / DefaultNo package declaredSmall programs, testing

Perfect! Let’s cover Non-Access Modifiers in Java in full detail. These are modifiers that do not control access, but instead change behavior or properties of classes, methods, or variables.


Non-Access Modifiers in Java


1. What is a Non-Access Modifier?

  • Definition: Modifiers that modify behavior of classes, methods, or variables without affecting access control.

  • Used for: class, method, variable


2. Types of Non-Access Modifiers

ModifierCan be applied toPurpose / BehaviorExample
finalClass, method, variable- Class: Cannot be extended

- Method: Cannot be overridden
- Variable: Constant value | final int x = 10;
final class Car {}
final void start(){} | | static | Method, variable, block, nested class | Belongs to class, shared by all objects | static int count = 0;
static void display(){} | | abstract | Class, method | - Class: Cannot create objects
- Method: Must be implemented by subclass | abstract class Vehicle { abstract void start(); } | | synchronized | Method, block | Thread-safe; only one thread can execute at a time | synchronized void increment() {} | | native | Method | Method implemented in other language (C/C++) | native void display(); | | transient | Variable | Not serialized during object serialization | transient String password; | | volatile | Variable | Ensures visibility of changes across threads | volatile int counter; | | strictfp | Class, method | Forces floating-point calculations to be platform-independent | strictfp class Calculator {} |


3. Detailed Examples

final

final class Car {} // cannot be extended
final int speed = 100; // constant
final void start() { System.out.println("Start"); } // cannot override

static

class Car {
    static int wheels = 4; // shared by all objects
    static void display() { System.out.println("Static method"); }
}

abstract

abstract class Vehicle {
    abstract void start(); // must be implemented in subclass
}
class Bike extends Vehicle {
    void start() { System.out.println("Bike started"); }
}

synchronized

class Counter {
    private int count = 0;
    synchronized void increment() { count++; } // thread-safe
}

native

class Example {
    native void display(); // implemented in C/C++
}

transient

class User implements java.io.Serializable {
    transient String password; // not saved during serialization
}

volatile

class Counter {
    volatile int count; // ensures thread visibility
}

strictfp

strictfp class Calculator {
    float divide(float a, float b) { return a / b; }
}

4. Quick Notes

  1. final, static, abstract are the most commonly used.

  2. transient, volatile, synchronized, native, strictfp are mostly advanced and used in multithreading, serialization, and system-level programming.

  3. Cannot combine some modifiers:

    • abstract and final cannot be used together.

    • abstract and private cannot be used together.


✅ Summary Table

Non-Access ModifierApplicable ToPurpose
finalClass, Method, VariableConstant, prevent inheritance/overriding
staticMethod, Variable, Block, ClassShared by class, not object
abstractClass, MethodPartial implementation, force subclass implementation
synchronizedMethod, BlockThread-safe execution
nativeMethodImplemented in other language
transientVariableSkip serialization
volatileVariableThread visibility
strictfpClass, MethodPlatform-independent floating-point

More from this blog

SS-JAVA

23 posts