π 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.
Modifier | Accessible within Class | Package | Subclass | Everywhere |
---|---|---|---|---|
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