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; }
}
ModifierEffect
publicVisible everywhere
(default)Package-private
finalCannot be subclassed
abstractCannot be instantiated
sealed JAVA 17+Restricted subclasses via permits

2. Creating Objects

MechanismSyntax
newnew ClassName(args)
Static factoryList.of(1,2,3)
Reflectioncls.getDeclaredConstructor().newInstance()
Cloningobj.clone() (Cloneable required)
DeserializationBypasses constructor

3. Declaring Instance Variables

AspectDetail
LocationInside class body, outside methods
Default accessPackage-private
Recommendationprivate + 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 { ... }
ComponentPurpose
Modifierspublic/private/static/final/abstract/synchronized
Return typeType or void
ParametersComma-separated, optionally varargs
throwsChecked exception declaration

5. Using this Keyword

UseMeaning
this.fieldDisambiguate from local/parameter
this(args)Call another constructor (must be first stmt)
this as refPass current object to method
OuterClass.thisOuter instance from inner class

6. Overloading Methods

Distinguished byExample
Parameter countprint(int) vs print(int,int)
Parameter typesprint(int) vs print(String)
Parameter orderfoo(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; }
}
RuleDetail
this(...)MUST be first statement
super(...)Cannot use both this and super

8. Understanding Static Members

MemberBehavior
Static fieldOne per class
Static methodNo this; cannot access instance state
Static nested classNo outer instance reference
AccessClassName.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"));
    }
}
AspectDetail
When runsOnce when class is loaded
AccessOnly static members
Can throwOnly unchecked or wrapped checked exceptions

10. Working with Instance Initializer Blocks

AspectDetail
SyntaxBare { ... } in class body
When runsBefore EACH constructor body
Use caseShared init across constructors (rare; prefer this(...))

11. Understanding Object Class Methods

MethodDefault Behavior
equals(Object)Reference identity
hashCode()Identity-based hash
toString()ClassName@hex
getClass()Runtime class
clone()Shallow copy (Cloneable required)
wait/notify/notifyAllSynchronization primitives
finalize() DEPRECATEDRemoved 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);
}
ContractRule
Reflexivex.equals(x) true
Symmetricx.equals(y)y.equals(x)
Transitivex=y, y=z ⇒ x=z
ConsistentRepeated calls return same result
Nullx.equals(null) false
Pair ruleIf equals returns true, hashCode MUST be equal

13. Understanding Clone Method

AspectDetail
InterfaceMust implement Cloneable marker
BehaviorField-by-field shallow copy
Mutable fieldsManually deep-copy in override
RecommendationPrefer copy constructors or static factories