Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala inheritance from Java class: select which super constructor to call

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?

like image 247
Phương Nguyễn Avatar asked Jul 26 '10 16:07

Phương Nguyễn


People also ask

Does a class inherit the constructor of its super class?

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.

Is super constructor inherited in Java?

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.

How do you call a super class constructor?

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.

Can we use super () and this () within the same constructor?

“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.


2 Answers

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.

like image 116
Landei Avatar answered Sep 21 '22 00:09

Landei


You have to append the constructor arguments to the class definition like this:

class B extends A("abc")
like image 43
Moritz Avatar answered Sep 22 '22 00:09

Moritz