'How does the inheritance of the constructor in Scala work?
class Point(val x: Int, val y: Int) {
def this(xArg: Int) = {
this(xArg, 0)
println("constructor")
}
}
class TalkPoint(x: Int, y: Int) extends Point(x, y) {
def talk() = {
println("my position is (" + x + "," + y + ")")
}
}
object Test {
def main(args: Array[String]): Unit = {
val p = new TalkPoint(0, 0)
p.talk()
}
}
Here is an example program in Scala. I am confused by the missing result "constructor " .
where is the constructor of the parent class Point ?
Solution 1:[1]
The constructor is actually part of the definition of the class:
class Point(val x:Int, val y:Int). This line defines not only Point's primary constructor that takes two Ints, by using val, it has made x and y read-only fields of the Point class. def this(xArg:Int) is what is called an auxiliary constructor, and notice how it calls the primary constructor (as all auxiliary constructors in Scala must do): this(xArg,0). In Java, Point's definition is roughly equivalent to
class Point {
public final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(int x) {
this(x,0);
System.out.println("constructor");
}
}
The line class TalkPoint(x:Int,y:Int) extends Point(x,y) not only defines the class TalkPoint, it also defines its primary constructor, declares it is a subclass of Point, and even calls Point's primary constructor. In Java, something like
class TalkPoint extends Point {
public TalkPoint(int x, int y) {
super(x, y);
}
// ...
}
In your main method, you call TalkPoint's primary constructor, which in turn calls Point's primary constructor, and at no point is Point's auxiliary constructor invoked, and thus nothing is printed. Try creating a Point, however, with its auxiliary constructor: val p = new Point(42)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anqit |
