COMMUNITY

Is it compiler error or feature?


(Olexandr Danylyshyn) #1

See to code below. Why does access to the private method work in this case?
In the project that I’m doing, this opportunity to call a private method turned out to be convenient, but I wanted to be sure that this would not be a mistake and would work in the future.

class Main {
    public static function main() {
        var a = new A();
        A.test(a); // It works!
    }
}


class A {
    public function new() {}
    
    public static function test(a:A):Void{
        a.f();
    }
    
    private function f():Void{
        trace('f');
    }
}

(Ludovic Bas) #2

test method is public and you access the private method f from a public method of A (f is only accessible from A). I guess it is normal.


(Olexandr Danylyshyn) #3

So, in a static function of class A, is it possible to call a private method on an instance of the same class A. This will always work?

 
class Main {
    public static function main() {
        A.test();
    }
}


class A {
    public function new() {}
    
    public static function test():Void {
        var a = new A();
        // f();    // error
        a.f();  // it works, access to private method
    }
    
    private function f():Void{
        trace('f');
    }
}


class B {
    public static function test():Void {
        var a = new A();
        // a.f();  // error
    }
}

(Olexandr Danylyshyn) #4

P.S. In Java, this also works. Probably this is the norm. OK.