Organizing Code with Packages
As your programs grow, you need a way to keep related files together. A package is a named folder for Java classes. You declare it at the top of a file with the package keyword. Other files use import to reach classes in other packages.
package com.example.shop;
import java.util.ArrayList;
import java.util.List;
public class Basket {
private List<String> items = new ArrayList<>();
public void add(String item) { items.add(item); }
public int count() { return items.size(); }
}Classes and Objects
A class is a blueprint. An object is a real thing built from that blueprint. A class can hold fields (data) and methods (actions). A constructor is a special method that runs when you create an object.
Counter c = new Counter(0); // "new" builds an object
c.increment();
System.out.println(c.get()); // prints 1Encapsulation and Access Control
Encapsulation means hiding the inside of a class. Mark fields private so outsiders cannot change them directly, and offer public methods as the only doorway. This protects your data and lets you change the inside later without breaking other code.
Static Members
A static member belongs to the class itself, not to any one object. There is exactly one copy, shared by all.
class MathBox {
static int calls = 0; // shared by every MathBox
int value; // each object has its own
}Inheritance
A class can extend another class and inherit its fields and methods. The child gets a head start and can add or change behavior. Use super to reach the parent's version.
Polymorphism and Overriding
Overriding means a child class replaces a parent's method with its own version. Polymorphism means you can treat different objects the same way and each responds in its own way.
Animal a = new Dog();
System.out.println(a.speak()); // "Woof" — the Dog's version runsAbstract Classes and Interfaces
An abstract class is a blueprint that cannot be built directly; it may leave some methods unfinished for children to fill in. An interface is a pure promise: a list of methods a class must provide. Classes can implement many interfaces but extend only one class.
Exercise
Why make a field private instead of public?
Show answer
So outside code must go through the class's methods to reach it. The class controls access and can change its internals safely later.
Spotted a mistake, or code that does not work?