我正在准备期末考试,并试图解决课本后面的练习题,这时我遇到了这个问题:
In Java, if the concrete type of p is Foo, p.getClass() and Foo.class will return the same thing. Explain why a similar equivalence could not be guaranteed to hold in Ruby, Python, or JavaScript.
任何人都可以阐明这一点吗?提前致谢!
最佳答案
Ruby、Python 和 JavaScript 都是动态类型语言,但这不是静态类型与动态类型的问题。相反,我认为这与 Java 的 getClass()
是最终的(不能被重写)有关,而其他语言没有这样的限制:
# Ruby
class Foo
def class()
return String
end
end
String.new().class() == String # => true
Foo.new().class() == Foo # => false
# Python
class Foo: pass
class Bar: pass
p = Foo()
p.__class__ == Foo # => True
p.__class__ = Bar
p.__class__ == Foo # => False
// JavaScript
function Foo() { }
function Bar() { }
var p = new Foo();
p.constructor == Foo; // => true
p.constructor = Bar;
p.constructor == Foo; // => false
有趣的是,在Python的情况下,设置__class__
成员实际上会影响方法查找,因此可以说p
的具体类型现在是Bar
,这并不违反等价性。
关于java - 与其他语言相比,Java 中的具体类型和抽象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20451690/