Working with Classes and Objects
1. Defining Classes
Example: Class declaration
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
}
| Modifier | Effect |
|---|---|
public | Visible everywhere |
| (default) | Package-private |
final | Cannot be subclassed |
abstract | Cannot be instantiated |
sealed JAVA 17+ | Restricted subclasses via permits |
2. Creating Objects
| Mechanism | Syntax |
|---|---|
new | new ClassName(args) |
| Static factory | List.of(1,2,3) |
| Reflection | cls.getDeclaredConstructor().newInstance() |
| Cloning | obj.clone() (Cloneable required) |
| Deserialization | Bypasses constructor |
3. Declaring Instance Variables
| Aspect | Detail |
|---|---|
| Location | Inside class body, outside methods |
| Default access | Package-private |
| Recommendation | private + accessor methods |
4. Defining Methods
Example: Method signatures
public int add(int a, int b) { return a + b; }
public <T> List<T> singleton(T item) { return List.of(item); }
public final void log(String msg) { ... } // cannot override
public static int max(int a, int b) { ... } // class-level
public abstract void render(); // no body
public void deprecated() throws IOException { ... }
| Component | Purpose |
|---|---|
| Modifiers | public/private/static/final/abstract/synchronized |
| Return type | Type or void |
| Parameters | Comma-separated, optionally varargs |
throws | Checked exception declaration |
5. Using this Keyword
| Use | Meaning |
|---|---|
this.field | Disambiguate from local/parameter |
this(args) | Call another constructor (must be first stmt) |
this as ref | Pass current object to method |
OuterClass.this | Outer instance from inner class |
6. Overloading Methods
| Distinguished by | Example |
|---|---|
| Parameter count | print(int) vs print(int,int) |
| Parameter types | print(int) vs print(String) |
| Parameter order | foo(int,String) vs foo(String,int) |
Warning: Return type alone does NOT distinguish overloads.
7. Overloading Constructors
Example: Constructor chaining
public class Rectangle {
private int width, height;
public Rectangle() { this(1, 1); }
public Rectangle(int side) { this(side, side); }
public Rectangle(int w, int h) { this.width = w; this.height = h; }
}
| Rule | Detail |
|---|---|
this(...) | MUST be first statement |
super(...) | Cannot use both this and super |
8. Understanding Static Members
| Member | Behavior |
|---|---|
| Static field | One per class |
| Static method | No this; cannot access instance state |
| Static nested class | No outer instance reference |
| Access | ClassName.member |
9. Using Static Blocks
Example: Static initializer
public class Config {
static final Map<String,String> SETTINGS;
static {
SETTINGS = new HashMap<>();
SETTINGS.put("env", System.getenv("APP_ENV"));
}
}
| Aspect | Detail |
|---|---|
| When runs | Once when class is loaded |
| Access | Only static members |
| Can throw | Only unchecked or wrapped checked exceptions |
10. Working with Instance Initializer Blocks
| Aspect | Detail |
|---|---|
| Syntax | Bare { ... } in class body |
| When runs | Before EACH constructor body |
| Use case | Shared init across constructors (rare; prefer this(...)) |
11. Understanding Object Class Methods
| Method | Default Behavior |
|---|---|
equals(Object) | Reference identity |
hashCode() | Identity-based hash |
toString() | ClassName@hex |
getClass() | Runtime class |
clone() | Shallow copy (Cloneable required) |
wait/notify/notifyAll | Synchronization primitives |
finalize() DEPRECATED | Removed in Java 18+; use Cleaner |
12. Implementing equals() and hashCode()
Example: equals + hashCode
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User u)) return false;
return id == u.id && Objects.equals(email, u.email);
}
@Override
public int hashCode() {
return Objects.hash(id, email);
}
| Contract | Rule |
|---|---|
| Reflexive | x.equals(x) true |
| Symmetric | x.equals(y) ⇔ y.equals(x) |
| Transitive | x=y, y=z ⇒ x=z |
| Consistent | Repeated calls return same result |
| Null | x.equals(null) false |
| Pair rule | If equals returns true, hashCode MUST be equal |
13. Understanding Clone Method
| Aspect | Detail |
|---|---|
| Interface | Must implement Cloneable marker |
| Behavior | Field-by-field shallow copy |
| Mutable fields | Manually deep-copy in override |
| Recommendation | Prefer copy constructors or static factories |