Angel Manuel Elias
Angel Manuel Elias

Reputation: 123

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.

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.

Upvotes: 1

Views: 832

Answers (3)

LPt
LPt

Reputation: 11

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.

Upvotes: 1

Mureinik
Mureinik

Reputation: 312219

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 ClassCastExceptions:

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

Upvotes: 1

JustAnotherDeveloper
JustAnotherDeveloper

Reputation: 2266

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.

Upvotes: 1

Related Questions