How does a subclass in Scala assign values to its parent class?
In Scala, the method for subclasses to assign values to the superclass is by calling the parent class’s constructor. When defining its own constructor, a subclass can use the ‘super’ keyword to call the parent class’s constructor and pass the necessary parameters.
For example, let’s say we have a parent class called Person and a child class called Student, you can assign values to the parent class like this:
class Person(name: String, age: Int) {
// 父类的构造函数
}
class Student(name: String, age: Int, school: String) extends Person(name, age) {
// 子类的构造函数
}
In the given example, the subclass Student invokes the constructor of the parent class Person for assignment. When instantiating a subclass object, the parent class constructor is first called to initialize the parent class properties, followed by initializing the subclass properties.
It should be noted that if the parent class does not have a default constructor with no parameters, the subclass needs to provide the necessary parameters when calling the parent class’s constructor.