Η κατάσταση ενός αντικειμένου ορίζεται από τις τιμές των πεδίων του (instance variables). Η σωστή διαχείρισή της είναι κρίσιμη για robust, thread-safe και maintainable κώδικα.
private.public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
setAge(age); // validation μέσω setter
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) {
if (age >= 0) this.age = age;
else throw new IllegalArgumentException("Η ηλικία δεν μπορεί να είναι αρνητική");
}
}
final και private.public final class ImmutablePoint {
private final int x, y;
public ImmutablePoint(int x, int y) { this.x = x; this.y = y; }
public int getX() { return x; }
public int getY() { return y; }
}
Οφέλη: Thread-safety, απλότητα, ασφαλής caching.
synchronized methods/blocks.java.util.concurrent.locks.Lock για fine-grained control.AtomicInteger, AtomicReference).public class Counter {
private int count = 0;
public synchronized void increment() { count++; }
public synchronized int getCount() { return count; }
}
Serializable για αποθήκευση/μετάδοση κατάστασης.transient για πεδία που δεν сериалиζονται.writeObject/readObject για ελεγμένη deserialization.public record Point(int x, int y) {}
// Αυτόματα: constructor, getters, equals, hashCode, toString
public πεδία.Πνευματικά δικαιώματα © Γνώση Υπολογιστών Όλα τα δικαιώματα διατηρούνται.