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;
Yes. You can use the static method if it is declared as public : public static void f() { // ... }
Static methods can't access instance methods and instance variables directly. They must use reference to object.
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.
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.
it seems possible to define static methods (via
sub
keyword) and static attributes (viamy
) 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 sub
s and our
variables. our
is the declarator used to define a lexical that is also for use outside the package it's declared withing. (my
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With