java - 从java中的父类型引用访问子属性
问题描述
当我像这样创建具有父引用的子对象时,Parent p = new Child();
基本上它是具有父引用和父子属性的子对象。然后,如果它是具有父类型引用的子对象,那么为什么我不能用它访问子属性。
我正在尝试做以下事情:
class Parent {
}
class Child extends Parent {
int a = 20;
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.a); //gives compile time error
// question is , p is parent type reference variable , but it is pointing to object of child
// class, then we should be able to access child properties from it, but we cant, why ?
}
解决方案
您可以通过对子类型的引用进行类型转换来做到这一点。
class Parent {
}
class Child extends Parent {
int a = 20;
public static void main(String[] args) {
Parent p = new Child();
System.out.println(((Child)p).a);
}
}
p
如果不是子类型的对象,它将抛出 ClassCastException 。因此,最好 通过运算符检查它p
是否是 Child 的对象instanceof
if (p instancof Child) {
System.out.println(((Child)p).a);
}
推荐阅读
- kotlin - Kotlin - How does Boolean? in if expression works on bytecode
- java - java.io.EOFException 引发的错误异常
- python - How do I make Python code to execute only once?
- xcode - 在 Xcode 中禁用#imageLiteral(resourceName: <..>) 预览?
- c# - AspNet Core 中 UTC 的 Http 查询参数
- javascript - 在以 innerHTML 加载的页面中显示 JavaScript 变量
- android - Google Play 服务地图中的 java.lang.StackOverflowError
- .net - Powershell [System.IO.Compression.ZipArchiveEntry] 不包含名为“ExtractToFile”的方法
- php - 在本地主机上找不到 URL
- php - 不再支持 /e 修饰符