user_1357
user_1357

Reputation: 7940

Extending new instance of a class

Hi I am trying to understand the code below for Scala. You have class B, and A which has dependency to the class B. Finally class C which extends A. When extending the class A code below is newing the B. What is significant of doing this? In Java you can't do this.

  class B {}
  class A( b:B ) {}
  class C extends A( new B) {}

Upvotes: 0

Views: 53

Answers (2)

Toxaris
Toxaris

Reputation: 7276

What is B?

class B {}

This is just an empty class. In Java, you would write the same.

What is A?

class A(b: B) {}

This is a class with one field. The constructor of the class takes one argument. The constructor sets the field to the argument. In Java, you would write this as follows:

class A {
  B b
  A(B b) {
    this.b = b
  }
}

What is C?

class C extends A(new B) {}

This is a subclass of A that sets the field b to new B. In Java, you would write this as follows:

class C extends A {
  C() {
    super(new B())
  }
}

Upvotes: 2

Lee
Lee

Reputation: 144206

class C extends A(new B) {}

means that C has a no-argument primary constructor and on construction it calls the base class constructor with a new B instance. It is equivalent to:

public class C extends A
{
    public C() {
        super(new B());
    }
}

Upvotes: 2

Related Questions