Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access static methods and attributes outside the class in Raku?

In raku it seems possible to define static methods (via sub keyword) and static attributes (via my) Those can be referenced inside the same class.

However, is it possible to access those methods and attributes outside of the class?

Something similar to this:

class MyClass {
    my $attribute = 123;
    sub my-method {
        say 'Hello';
    }
}

MyClass.$attribute;
MyClass.my-method;
like image 516
Julio Avatar asked Jul 15 '20 17:07

Julio


People also ask

Can we access static method outside the class?

Yes. You can use the static method if it is declared as public : public static void f() { // ... }

Can a static attribute be accessed inside of an instance method?

Static methods can't access instance methods and instance variables directly. They must use reference to object.

Can a static method can access modify the attributes of a class?

Static methods can be bound to either a class or an instance of a class. Static methods serve mostly as utility methods or helper methods, since they can't access or modify a class's state. Static methods can access and modify the state of a class or an instance of a class.

How can we access static method in non-static method?

The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs. This confusion is the main reason why you see this question on core Java interview as well as on core Java certifications e.g. OCAJP and OCPJP exam.


Video Answer


1 Answers

it seems possible to define static methods (via sub keyword) and static attributes (via my) Those can be referenced inside the same class.

I can see why you're calling them static methods and attributes but Raku has a much simpler solution for those:

class MyClass {        
    method my-method {
        say 'Hello';
    }
    method attribute is rw {
      state $attribute = 123
    }
}

say MyClass.attribute;   # 123
MyClass.attribute = 99;
say MyClass.attribute;   # 99
MyClass.my-method;       # Hello

You could use our subs and our variables. our is the declarator used to define a lexical that is also for use outside the package it's declared withing. (mys are never shared; a sub declarator without an our is the same as my sub.)

So:

class MyClass {        
    our sub my-sub {
        say 'Hello';
    }
    our $attribute = 123
}
import MyClass;
say $MyClass::attribute;   # 123
$MyClass::attribute = 99;
say $MyClass::attribute;   # 99
MyClass::my-sub;           # Hello

As you can see, these aren't methods; this approach ignores OOP in the sense the prior solution does not.

like image 63
raiph Avatar answered Oct 19 '22 17:10

raiph