Skip to content

πŸ“¦ Java Packages, Access Modifiers, and the static Keyword

πŸ”– Introduction

In Java, organizing your code and controlling access is essential as your project grows. This lesson introduces:

  • Packages – organize classes logically
  • Access Modifiers – control who can use what
  • The static keyword – shared methods and variables

Let’s break them down with examples πŸ‘‡

πŸ“ Java Packages – Organizing Classes


βœ… What is a Package?

A package is a namespace that groups related classes and interfaces. Think of it as a folder in your project.

package myapp.utils;

public class Helper {
    public static void sayHi() {
        System.out.println("Hi from Helper!");
    }
}

πŸ“Œ Using a Class from Another Package

import myapp.utils.Helper;

public class Main {
    public static void main(String[] args) {
        Helper.sayHi();
    }
}

πŸ’‘ Why Use Packages?

  • Avoid class name conflicts
  • Organize files logically
  • Control access using modifiers

πŸ” Access Modifiers in Java

Access modifiers define who can access a class, method, or variable.

ModifierAccessible within ClassPackageSubclassEverywhere
privateβœ…βŒβŒβŒ
(default)βœ…βœ…βŒβŒ
protectedβœ…βœ…βœ…βŒ
publicβœ…βœ…βœ…βœ…

πŸ” Example of All Modifiers

public class Example {
    private int secret = 123;
    int defaultValue = 10;         // package-private
    protected int inherited = 50;
    public int visibleEverywhere = 100;
}

βš™οΈ The static Keyword – Shared Across Objects


βœ… What is static?

  • Belongs to the class, not instances
  • Memory is allocated once
  • Accessed using the class name

πŸ”Ή Static Variable Example

class Counter {
    static int count = 0;

    Counter() {
        count++;
    }
}

Usage:

public class Test {
    public static void main(String[] args) {
        new Counter();
        new Counter();
        System.out.println(Counter.count);  // 2
    }
}

πŸ”Έ Static Method Example

class MathUtils {
    static int square(int x) {
        return x * x;
    }
}

Usage:

System.out.println(MathUtils.square(5));  // 25

πŸ’‘ Quick Tip

You can access static methods/variables without creating an object.

πŸ§ͺ Challenge: Static ID Generator

class Employee {
    static int nextId = 1;
    int id;

    Employee() {
        id = nextId++;
    }
}

public class Company {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();
        System.out.println(e1.id); // 1
        System.out.println(e2.id); // 2
    }
}

βœ… What You Learned

  • Packages group related classes
  • Access Modifiers control visibility
  • static members belong to the class, not the instance

Tags:

Leave a Reply

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