关于Java中对象类型转换的问题
我有一个关于 Java 中类型转换的问题,如下所示:
假设我有一个类:
class A { public void m() }
现在我有:
A a1 = new A(); // (1)
a1.m(); // (2)
Object o = new A(); // (3)
o.m(); // (4)
我们可以将第 (1) 行说成: a1
包含新对象 的内存地址A()
(在堆中创建)。所以第(2)行绝对没问题。
我们也可以将第 (3) 行说成: o
包含新对象 A()
(也在堆中创建)的内存地址。但第(4)行显然无法编译,因为Object类没有m()方法。
但为什么a1
包含对象A()
的地址,并且它“可以看到”m()
方法;而o
也包含对象A()
的地址,但它“看不到”m()
方法?
还有其他解释吗? (除了 Object
类没有 m()
方法的原因)。
谢谢大家。
I have a question regarding type conversion in Java as follows:
suppose I have a class:
class A { public void m() }
Now I do:
A a1 = new A(); // (1)
a1.m(); // (2)
Object o = new A(); // (3)
o.m(); // (4)
We can say line (1) as: a1
contains the memory address of the new object A()
(created in Heap). So line (2) is definitely ok.
We can also say line (3) as: o
contains the memory address of the new object A()
(also, created in Heap). But line (4) obviously cannot be compiled because the Object class does not have the m() method.
But why a1
contains the address of object A()
, and it "can see" the m()
method; while o
also contains the address of object A()
, but it "cannot see" the m()
method?
Is there any other explanation? (Except the reason that Object
class does not have the m()
method).
Thanks all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是解释。这些东西是在编译时验证的。想象一下以下情况:
现在,
A
有m()
,但String
没有。这由编译错误表示。如果 Java 不是静态类型,则此错误将在运行时出现。并且认为问题发现得越早越好。That is the explanation. These things are verified at compile-time. Imagine the following:
Now,
A
hasm()
, butString
does not. And this is indicated by a compilation error. If Java was not statically typed, this error would appear at run-time. And it is considered that the earlier the problem is discovered, the better.