简体   繁体   English

java中如何投亲子班?

[英]How to cast parent-child classes in java?

I am faced with an implementation question.我面临一个实施问题。 The question is whether it is possible to cast "grandfather" to "child" in java.问题是是否可以在 java 中将“祖父”转换为“孩子”。

For example:例如:

This is the parent class这是父 class

  public class IDDocument {
    public IDDocument() {
    }
  }

This is the class that inherits from its parent called IDDocument这是从名为 IDDocument 的父级继承的 class

  public class Passport extends IDDocument {
    public Passport() {
    }
  }

And now, there is this class that inherits from Passport现在,有这个继承自 Passport 的 class

  public class SLPassport extends Passport {
    public SLPassport() {
    }
  }

Knowing this, I want to know if it is possible to cast IDDocument to SLPassport.知道了这一点,我想知道是否可以将 IDDocument 转换为 SLPassport。

This problem arose from the fact that the information that I receive from a service is contained in an IDDocument type, but I also need data that is only contained in SLPassport and it is necessary to use IDDocument.这个问题源于我从服务接收到的信息包含在 IDDocument 类型中,但我还需要仅包含在 SLPassport 中的数据,并且必须使用 IDDocument。

Previously, I was able to cast Passport to IDDocument like this:以前,我可以像这样将 Passport 转换为 IDDocument:

((Passport) idDocument).getSomeMethod();

So I retrieved data that only the child class contains.所以我检索到只有子 class 包含的数据。

Now as I said, my goal is to capture data but from the passport child class with IDDocument.现在正如我所说,我的目标是从带有 IDDocument 的护照子 class 中捕获数据。

If you have a class A, a class B that inherits from A, and a class C that inherits from B, class C also inherits from A. Here's an explanation of polymorphism that's relevant to your question. If you have a class A, a class B that inherits from A, and a class C that inherits from B, class C also inherits from A. Here's an explanation of polymorphism that's relevant to your question.

The short answer is yes, assuming the instance is really an SLPassport instance.简短的回答是肯定的,假设该实例确实是一个SLPassport实例。 I'd also suggest you explicitly check this before casting in order to avoid ClassCastException s:我还建议您在强制转换之前明确检查这一点,以避免ClassCastException

if (idDocument instanceof SLPassport) {
    ((SLPassport) idDocument).doSomethingSpecific();
} else {
    System.err.println("Not an SLPassport"); // Or some better error handling
}

An SLPassport object can be cast to: IDDocument, Passport, Object or SLPassport SLPassport object可以转换为:IDDocument、Passport、Object 或 SLPassport

So if you did something like:因此,如果您执行以下操作:

Passport myPass = new SLPassport();
SLPassport mySlPass = (SLPassport) myPass;

it would be valid.这将是有效的。

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

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