反射、继承和java

发布于 2024-12-12 13:52:56 字数 1436 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

寄离 2024-12-19 13:52:57

超类构造函数始终在子类构造函数之前运行。因此,子类的实例永远不会处于可供使用的就绪状态。

SuperClass constructor is always run before the child class's. So the instance of child class is never in ready state to be used as such.

温柔嚣张 2024-12-19 13:52:57

难道不可能吗,因为动物的构造函数主体是在马的构造函数主体之前调用的。对象的马“部分”尚不存在。

Is it not possible, because constructor body of animal is invoked before body of constructor horse. Horse 'part' of object doesn't exist yet.

匿名。 2024-12-19 13:52:57

超类的构造函数(或者其他任何东西)不应该访问子类特定的方法;超类不应该知道从它派生的类的任何信息。

就此而言,超类不应该调用子类在其构造函数中定义的方法,因为该对象尚未初始化。 这里有一些关于此的讨论,并举例说明。

A superclass's ctor (or anything else, really) shouldn't be accessing sub-class-specific methods; the superclass should not know anything about classes that derive from it.

For that matter, superclasses shouldn't call methods defined by subclasses in its ctor because the object hasn't been initialized yet. Here's some discussion regarding that, with examples.

oО清风挽发oО 2024-12-19 13:52:57

如果您有一个 Horse 的实例,那么无论您在哪里(包括 Animal 构造函数),您都可以访问该实例的所有方法/字段。

但是,如果您位于普通的 Animal 或其他子类中,则无法访问 Horse 的方法/字段,因为它不是 Horse。

If you have an instance of a Horse, it doesn't matter where you are (including int he Animal constructor) you can access all the methods/fields of that instance.

However, if you are in a plain Animal or some other subclass, you can't access methods/fields of Horse because its not a Horse.

一瞬间的火花 2024-12-19 13:52:57

是的,也不是。如果您位于构造函数中,则可以通过反射 API 访问子类(或任何类)的方法。就良好实践而言,那就不行,因为动物不是马。

Yes and no. Via the reflection API you can access the methods of a subclass (or any class) if you're in a constructor. In terms of good practice, then no since an animal is not a horse.

此刻的回忆 2024-12-19 13:52:57

要实现的重要一点是java加载类的方式:首先加载超类,然后加载子类。

如果您需要访问特定于子类的方法,则必须找到另一种方法。

例如,一种策略是使用接口或继承将子类正在履行的一些契约嵌入到超类中......

The important thing to realize is the way that java loads classes : first the superclass is loaded, and then the subclasses.

if you need to access methods that are specific to the subclass, you will have to find another methodology.

One strategy , for example, would to embed some of the contract which your subclass is fulfilling in the superclass using interfaces or inheritance....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文