Is sta开发者_开发知识库tic in Java like self in Ruby?
No. Java's static and Ruby's self have absolutely nothing whatsoever to do with each other.
The Java equivalent to Ruby's self is this. The Ruby equivalent to Java's static does not exist.
Java's static means that the method is dispatched statically instead of dynamically. In Ruby, methods are always dispatched dynamically. static means that the method is not called on any object. In Ruby, methods are always called on objects. Since static methods in Java aren't associated with any object, they don't have access to any object state. In Ruby, methods always have access to the state of their associated instance.
In short, static methods aren't really methods at all, they are procedures. Ruby doesn't have procedures, it only has (instance) methods.
There is no construct in Ruby that would even be remotely equivalent to Java's static.
So-called "Class methods" are not static methods.
When you do
class MyClass
def self.do_something
# Do awesome stuff
end
end
self merely refers to MyClass. (Do class MyClass; puts self.inspect; end if you don't believe me!) You can replace self with MyClass, or even something that refers to the class MyClass, and you'd have the same result.
You could do
class MyClass
end
foo = MyClass
def foo.do_something
# Do awesome stuff
end
and you'll get the same results.
And, you can do the same stuff on something that isn't a class
my_string = "HAI WORLD"
def my_string.do_something
# Yet more awesome stuff
end
and you can then call my_string.do_something
Would calling do_something on my_string be a static method?
So self doesn't magically make a method static.
加载中,请稍侯......
精彩评论