Ciberman
Ciberman

Reputation: 924

Property 'foo' is protected and only accesible through an instance of class 'Foo' (in instances of Foo)

I have the following code in my Typescript. But it reports the following error in the child._moveDeltaX(delta) line:

ERROR: Property '_moveDeltaX' is protected and only accesible 
       through an instance of class 'Container'   
INFO:  (method) Drawable._moveDeltaX( delta:number):void

The code is the folowing:

class Drawable {

    private _x:number = 0;

    constructor() {}

    /**
     * Moves the instance a delta X number of pixels
     */
    protected _moveDeltaX( delta:number):void {
        this._x += delta;
    }
}

class Container extends Drawable {
    // List of childrens of the Container object 
    private childs:Array<Drawable> = [];

    constructor(){ super();}

    protected _moveDeltaX( delta:number ):void {
        super._moveDeltaX(delta);
        this.childs.forEach( child => {
            // ERROR: Property '_moveDeltaX' is protected and only accesible
            //        through an instance of class 'Container'
            // INFO:  (method) Drawable._moveDeltaX( delta:number):void
            child._moveDeltaX(delta);
        });
    }
}

What do I have wrong? I thought that you can access to a protected method. In other lenguajes this code would work without problem.

Upvotes: 1

Views: 1112

Answers (2)

user3285954
user3285954

Reputation: 4749

Casting to any is a dirty hack. The proper solution would be to separate the interface from access levels:

  1. Create an IDrawable interface with the methods of a Drawable object i.e. moveDeltaX.
  2. Container in this case doesn't inherit from IDrawable, instead the list will hold IDrawable objects: private children: Array = [];
  3. The actual children i.e. Rectangle, Circle will have IDrawable interface as base, this will ensure that the base methods can be accessed regardless of the referenced type.
  4. If you'd like to share some base implementation then you can create a Drawable class that implements IDrawable (or DrawableBase class, and Drawable interface) and use that as base for the concrete types.

It's not very relevant in javascript and TypeScript, but in languages with better OO support the interfaces allow to easily change implementation without having to modify most of the application.

Upvotes: 0

Vaccano
Vaccano

Reputation: 82341

You "childs" object is not in in visibility of the inherited object. You just made a new instance that cannot access the protected method. You can access the protected methods using super, but not for other instances.

This would fail in c# as well (I think).

Upvotes: 1

Related Questions