Objects and interfaces¶
Encapsulation¶
Encapsulation keeps state and the operations that protect it together:
final class Account {
private long balance;
void deposit(long amount) {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
balance += amount;
}
long balance() {
return balance;
}
}
Private fields provide access control; methods preserve the object's invariants.
Inheritance and polymorphism¶
abstract class Shape {
abstract double area();
}
final class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
A class can extend one class and implement multiple interfaces.
Interfaces¶
Modern interfaces may declare abstract, default, static, and private methods. Interface fields are implicitly public static final. Interfaces cannot be instantiated directly.
An abstract class that implements an interface may leave methods unimplemented. A concrete subclass must provide the remaining implementations.
Creating objects¶
The normal construction syntax is:
Reflection, cloning, deserialization, factories, and dependency-injection frameworks can also produce objects, but they are specialized mechanisms rather than replacements for constructors.
Verified repository programs¶
Runnable Deterministic output Stable Java
Run the polymorphism example:
java --enable-preview \
-cp build/classes/java/main:build/resources/main \
nitin.a5object.AnimalDoctor
Run the interface example:
java --enable-preview \
-cp build/classes/java/main:build/resources/main \
nitin.a6oops.interfaces.AnotherServiceProvider
Both outputs are verified by scripts/verify-doc-examples.sh.
Repository examples¶
src/main/java/nitin/a5objectsrc/main/java/nitin/a6oopssrc/main/java/nitin/a6oops/interfaces/I1InterfaceMethod.javasrc/main/java/nitin/nestedClassessrc/main/java/nitin/cloning