12 Aralık 2024 Perşembe

Java record İle Yapılamayacak Şeyler

1. Records Cannot Extend Another Class
2. Records Cannot Be Extended
Örnek
Şu kod derlenmez
public class PremiumRecord extends InsuranceRecord {…}
3. Records Cannot Have Additional Instance Fields
Örnek
Şu kod derlenmez
public record InsuranceRecord(String type, float premium) {
  private String policyNumber;  // This won't compile
}
4. Private Canonical Constructors Are Not Allowed
Örnek
Şu kod derlenmez
public record InsuranceRecord(String type, float premium) {
  private InsuranceRecord(String type, float premium) {
    this.type = type;
    this.premium = premium;
  }
  public static InsuranceRecord newInstance(String type, float premium) {
    return new InsuranceRecord(type, premium);
  }
}
5.  Records Cannot Have Setters
Örnek
Şu kod derlenmez
public record InsuranceRecord(String type, float premium) {
  public void setType(String type) {
    this.type = type;  // Won't compile
  }
}