I have multiple constructor in a Java class.
public class A{
public A(){...}
public A(String param){...}
public A(String param, Object value}
}
Now I want to create a Scala class that inherit from that class
class B extends A{
super("abc")
}
But this syntax is invalid. Scala is complaining that '.' expected but '(' found.
What is the valid way to do this?
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Constructors are not inherited. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.
“this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement). “this” can be passed as an argument in the method and constructor calls.
As Moritz says, you have to provide the constructor args directly in the class definition. Additionally you can use secondary constructors that way:
class B(a:String, b:String) extends A(a,b) {
def this(a:String) = this(a, "some default")
def this(num:Int) = this(num.toString)
}
But you must refer to this
, super
is not possible.
You have to append the constructor arguments to the class definition like this:
class B extends A("abc")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With