Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

elegant Java class downcast

Let A be a superclass of AB and AC. Given a method:

public void handleStuff(A someObject) {
  if(someObject instanceof AB){ 
     ((AB)someObject).someABFunction();
  } else if(someObject instanceof AC) {
     ((AC)someObject).someACFunction();
  }
}

I don’t like the double checking/casting operation here; is there any other way to code this without first checking for a type and then casting? I know I could do it with two overloaded functions that take AB or AC as parameters, but I was looking for less code, not more 🙂 Something like:

public void handleStuff(A someObject) {
  if(someObject instanceof AB){ 
     someObject.someABFunction(); // it is already clear that this is AB
  } else if(someObject instanceof AC) {
     someObject.someACFunction(); // it is already clear that this is AC
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

On Java 16 and newer, you can use pattern matching to avoid the cast. Like this:

public void handleStuff(A someObject) {
  if (someObject instanceof AB ab) { 
     ab.someABFunction();
  } else if (someObject instanceof AC ac) {
     ac.someACFunction();
  }
}

On Java 17 and newer, you can enable the preview feature for pattern matching in switch-expressions to shorten it further. With that feature, you can do this:

public void handleStuff(A someObject) {
  switch (someObject) {
    case AB ab -> ab.someABFunction();
    case AC ac -> ac.someACFunction();
    default -> {}
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading