Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class extend itself?

Tags:

scala

I am reading the source code of Spark. I see it seems a class extends itself.

My questions: does it extend itself? If so, what's it called? Why do we do that?

class OneHotEncoderModel private[ml] (
    @Since("2.3.0") override val uid: String,
    @Since("2.3.0") val categorySizes: Array[Int])
  extends Model[OneHotEncoderModel] with OneHotEncoderBase with MLWritable
like image 633
Jill Clover Avatar asked Jun 07 '18 12:06

Jill Clover


People also ask

Does a class extend itself Java?

No, a class cannot extend itself in java.

Can a class extend a class?

Extending a Class. A class can inherit another class and define additional members. We can now say that the ArmoredCar class is a subclass of Car, and the latter is a superclass of ArmoredCar. Classes in Java support single inheritance; the ArmoredCar class can't extend multiple classes.

Can a class extend twice?

You can only Extend a single class. And implement Interfaces from many sources. Extending multiple classes is not available.

Can a class extend only one class?

A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.


1 Answers

It's not extending itself. Actually, "extends itself" has no meaning, or one could say all classes extends them-selves.

OneHotEncoderModel(...) extends Model[OneHotEncoderModel] with ...

means that OneHotEncoderModel extends Model. And Model is type-parametrized with OneHotEncoderModel. This construct allows Model to have the actual implementing class as a type-parameter and use it.

This can be used, for example, in an abstract api:

trait Model[A]{
  def join(other: A): A
}

Here, to be a Model sub-class, OneHotEncoderModel will have to implement def join(other: OneHotEncoderModel): OneHotEncoderModel

like image 92
Juh_ Avatar answered Oct 04 '22 18:10

Juh_