Daniel Robinson
Daniel Robinson

Reputation: 14848

access to inherited fields in dart

abstract class Painter {

    CanvasElement canvas;

    Painter(this.canvas);

    void draw();
}

class SpritePainter extends Painter{

    SpritePainter(this.canvas);

    void draw(){
        window.console.log("Drawing");
        window.console.log(canvas);
    }

}

using the above code my application fails when trying to call new SpritePainter(query('#sprite-canvas')); saying that this.canvas is an unknown field. I thought the CanvasElement in the abstract parent class is accessible to the sub class?

Update:

I fixed this with:

SpritePainter(CanvasElement canvas):super(canvas);

but then I read on dart tutorials that abstract classes can only have factory constructors?

Upvotes: 2

Views: 2825

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76183

You have to forward your param to the super constructor like the following :

abstract class Painter {
  CanvasElement canvas;

  Painter(this.canvas);

  void draw();
}

class SpritePainter extends Painter{
  SpritePainter(CanvasElement canvas) : super(canvas);

  void draw(){
    window.console.log("Drawing");
    window.console.log(canvas);
  }
}

Upvotes: 9

Related Questions