МОДУЛЬ 8 · УРОК 6
Object - Root of Everything
java.lang.Object is the mother of all classes. Every class extends Object.
30 minBeginnerJavaOOP
Object
Object sits at the top of the class hierarchy. Every class implicitly extends Object.
// These are equivalent:
class MyClass { }
class MyClass extends Object { }
toString()
Returns string representation. Default: ClassName@hashcode. Override for meaningful output.
@Override
public String toString() {
return "Person{" + name + "}";
}
equals()
Default: reference equality (==). Override for value equality.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person p = (Person) o;
return age == p.age && Objects.equals(name, p.name);
}
hashCode()
For hash-based collections (HashMap, HashSet).
@Override
public int hashCode() {
return Objects.hash(name, age);
}
If equals() returns true, hashCode() MUST return the same value!
Contract
- If equals() true, hashCode() must be same.
- If hashCode() same, equals() may be false.
- Always override both together. Use IDE generation.
IDE Generation
Right-click -> Generate -> equals() and hashCode(). Select fields that define identity. IDEs (IntelliJ, Eclipse) generate correct, reliable code.
✅ Итоги урока
- Object is the root superclass of all Java classes.
- toString(): string representation (override for meaningful output).
- equals(): value equality (override for logical comparison).
- hashCode(): hash value (MUST override when equals is overridden).
- Contract: equal objects must have equal hashCodes.
- IDE generates equals/hashCode reliably.
- String pool: literals are interned by default.
Congratulations! You completed Inheritance and Polymorphism module!
Test: Test: Object class
4 вопроса