How do records differ from traditional classes in Java?

Java MCQ: How do records differ from traditional classes in Java?

a) Records are mutable by default, while classes are immutable by default
b) Records automatically generate methods like equals(), hashCode(), and toString()
c) Records cannot implement interfaces
d) Records support inheritance, while classes do not

Answer:

b) Records automatically generate methods like equals(), hashCode(), and toString()

Explanation:

One of the key differences between records and traditional classes in Java is that records automatically generate methods like equals(), hashCode(), and toString(). When you define a record, the compiler automatically provides implementations for these methods based on the fields declared in the record.

For example, if you define a record like this:

public record Person(String name, int age) {}

The compiler automatically generates:

  • A constructor that initializes the fields name and age
  • Getter methods for the fields (name() and age())
  • An equals() method that compares the fields
  • A hashCode() method that computes a hash code based on the fields
  • A toString() method that returns a string representation of the record

Traditional classes, on the other hand, do not automatically generate these methods. Developers need to manually implement them, which can lead to boilerplate code and potential errors.

Additionally, records are immutable by default, meaning their fields cannot be modified after the record is created. This contrasts with traditional classes, which can have mutable fields unless explicitly made immutable.

Overall, records provide a more concise and streamlined way to define data-carrying classes in Java, with built-in immutability and automatically generated methods, reducing the need for boilerplate code.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top