英文:
How to cast parent-child classes in java?
问题
我面临一个实现问题。
问题是是否可以在Java中将“grandfather”强制转换为“child”。
例如:
这是父类:
public class IDDocument {
public IDDocument() {
}
}
这是从其父类IDDocument继承的类:
public class Passport extends IDDocument {
public Passport() {
}
}
现在,有这个从Passport继承的类:
public class SLPassport extends Passport {
public SLPassport() {
}
}
在了解这一点的基础上,我想知道是否可以将IDDocument强制转换为SLPassport。
这个问题源于我从服务中接收到的信息包含在IDDocument类型中,但我还需要仅包含在SLPassport中的数据,而且有必要使用IDDocument。
之前,我可以像这样将Passport强制转换为IDDocument:
((Passport) idDocument).getSomeMethod();
因此,我获取了仅子类包含的数据。
现在,正如我所说,我的目标是从Passport子类中捕获数据,同时使用IDDocument。
英文:
I am faced with an implementation question.
The question is whether it is possible to cast "grandfather" to "child" in java.
For example:
This is the parent class
public class IDDocument {
public IDDocument() {
}
}
This is the class that inherits from its parent called IDDocument
public class Passport extends IDDocument {
public Passport() {
}
}
And now, there is this class that inherits from Passport
public class SLPassport extends Passport {
public SLPassport() {
}
}
Knowing this, I want to know if it is possible to cast IDDocument to 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.
Previously, I was able to cast Passport to IDDocument like this:
((Passport) idDocument).getSomeMethod();
So I retrieved data that only the child class contains.
Now as I said, my goal is to capture data but from the passport child class with IDDocument.
答案1
得分: 1
如果您有一个类A,一个从A继承的类B,以及一个从B继承的类C,那么类C也从A继承。这里有一个与您的问题相关的多态性解释链接。
英文:
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.
答案2
得分: 1
简短的回答是,是的,前提是该实例确实是一个 SLPassport
实例。我还建议您在进行强制转换之前明确检查,以避免 ClassCastException
:
if (idDocument instanceof SLPassport) {
((SLPassport) idDocument).doSomethingSpecific();
} else {
System.err.println("Not an SLPassport"); // 或者进行更好的错误处理
}
英文:
The short answer is yes, assuming the instance is really an SLPassport
instance. I'd also suggest you explicitly check this before casting in order to avoid ClassCastException
s:
if (idDocument instanceof SLPassport) {
((SLPassport) idDocument).doSomethingSpecific();
} else {
System.err.println("Not an SLPassport"); // Or some better error handling
}
答案3
得分: 1
一个 SLPassport 对象可以转换为:
IDDocument(身份证明文件)、Passport(护照)、Object(对象)或 SLPassport(SL 护照)
因此,如果你执行了类似下面的操作:
Passport myPass = new SLPassport();
SLPassport mySlPass = (SLPassport) myPass;
这是有效的。
英文:
An SLPassport object can be cast to:
IDDocument, Passport, Object or SLPassport
So if you did something like:
Passport myPass = new SLPassport();
SLPassport mySlPass = (SLPassport) myPass;
it would be valid.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论