Junior — Middle
Can a Data Class in a programming language have inheritance capabilities?
sobes.tech AI
Answer from AI
Yes, in Kotlin, which is often used for Android app development, data classes can be inherited, but with some restrictions.
Data classes automatically generate methods like equals(), hashCode(), toString(), copy(), and componentN(), which are convenient for storing data. However, data classes are not open for inheritance by default, as they are declared with the final modifier.
If you need to inherit a data class, you should declare it with the open modifier, and the subclass does not necessarily have to be a data class. But inheritance of data classes is rare, as they are intended for simple data structures.
Example:
data class User(val name: String, val age: Int)
// Cannot inherit directly, as User is final
open data class Person(val name: String)
class Employee(name: String, val position: String) : Person(name)
Thus, inheritance is possible, but with caution and understanding of the limitations.