Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most specific subclass for a Java object?

I have two classes A and B, where B is subclass of A and A is not abstract. Therefore I can have objects that are instance of A and objects that are instance of B (and therefore of A).

How can I distinguish objects that are only instance of A?

Sure, I can write something like "object instaceof A && !(object instance of B)" but this is a very poor design since I'll need to change the code every time I add new subclasses to A. Better alternatives?

like image 327
Jordi Cabot Avatar asked Jun 19 '26 17:06

Jordi Cabot


2 Answers

object.getClass() == A.class
like image 182
Yishai Avatar answered Jun 21 '26 05:06

Yishai


Why you want them to distinguish? Usually this is the opposite of OO. You have different instances that you don't need to distinguish because the different implementation does everything right.

If you need to do so than there should be a protocol for it. Have a method for that purpose that returns something to recognize. That is more flexible,too.

I would instanceOf and getClass already consider bad style if this is used without good reason

like image 44
Norbert Hartl Avatar answered Jun 21 '26 07:06

Norbert Hartl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!