简体   繁体   English

您可以通过 Java 中的超级 class 访问子 class 变量吗

[英]Can you access sub class variable via super class in Java

Can I access my subclass variable via super class instance?我可以通过超级 class 实例访问我的子类变量吗?

For instance I create my super class object in Main, and then I want to know the value of variable in the sub class.例如,我在 Main 中创建了我的超级 class object,然后我想知道子 class 中的变量值。 Is it possible to do so?有可能这样做吗? Thanks.谢谢。

No this goes against the inheritance principle.不,这违反了 inheritance 原则。 It is like asking if a previous gen device will have access to the newer features introduced in the next gen device based on this.这就像询问上一代设备是否可以访问基于此的下一代设备中引入的新功能。

A subclass can access non private members of parent class but not vice versa.子类可以访问父 class 的非私有成员,反之则不行。 It doesnt make sense as the language syntax doesn't ever allow access to child from parent while the opposite is possible through methods and keywords like super.这是没有意义的,因为语言语法不允许从父级访问子级,而相反的情况可以通过诸如 super 之类的方法和关键字来实现。

So it is better that you rethink the way you are thinking of using inheritance abd refactor your core to meet the requirement as this certainly wont work因此,最好重新考虑使用 inheritance abd 重构您的核心以满足要求的方式,因为这肯定行不通

If class B extends class A and you have an A object, then you can always convert it to its subclass, B in this case.如果 class B 扩展 class A 并且您有一个 A object,那么您始终可以将其转换为其子类,在这种情况下为 B。 Consider the following:考虑以下:

A a = new A();
B b = (B)a;

afterwards, you can always reach B members via b.之后,您始终可以通过 b 联系 B 成员。 You can do it in an inline manner as well, via ((B)a) .您也可以通过((B)a)以内联方式执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM