gpt4 book ai didi

java - 与其他语言相比,Java 中的具体类型和抽象类型

转载 作者:行者123 更新时间:2023-11-29 19:44:51 26 4
gpt4 key购买 nike

我正在准备我的期末考试,当我遇到这个问题时试图解决教科书后面的练习题:

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­()
retur­n Strin­g
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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com