I need to check if the instance is exactly of this type. But it seems that instanceof returns true also if the subtype is checked for a supertype (case 3). I have never known this before, and I am very surprised. Am I something wrong here? How do I accurately test this type?
//.. class DataSourceEmailAttachment extends EmailAttachment //... EmailAttachment emailAttachment = new EmailAttachment(); DataSourceEmailAttachment emailAttachmentDS = new DataSourceEmailAttachment(); if (emailAttachment instanceof EmailAttachment){ System.out.println(" 1"); } if (emailAttachment instanceof DataSourceEmailAttachment){ System.out.println(" 2"); } if (emailAttachmentDS instanceof EmailAttachment){ System.out.println(" 3 "); } if (emailAttachmentDS instanceof DataSourceEmailAttachment){ System.out.println(" 4"); }
RESULT:
1 3 4
I want to avoid case 3 , I only need "exact matches" (case 1 and 4), how can I check them?
java instanceof
jens
source share