java:instanceof

This is an old revision of the document!


A PCRE internal error occured. This might be caused by a faulty plugin

====== Τελεστής instanceof ====== Ο τελεστής ''instanceof'' επιστρέφει boolean true/false εάν ένα αντικείμενο ανήκει σε συγκεκριμένο τύπο δεδομένων. Με χρήση του τελεστή ''instanceof'' μπορούμε να εξετάσουμε εάν ένα αντικείμενο αποτελεί υλοποίηση μίας κλάσης ή υλοποιεί ένα συγκεκριμένο [[java:interface|interface]]. Δείτε το παρακάτω παράδειγμα. <code java MyInterface.java> public interface MyInterface { } </code> <code java Parent.java> public class Parent { } </code> <code java Child.java> public class Child extends Parent implements MyInterface { } </code> <code java InstanceofDemo.java> class InstanceofDemo { public static void main(String[] args) { Parent obj1 = new Parent(); Parent obj2 = new Child(); System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent)); System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent)); System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); } } </code> Το παραπάνω πρόγραμμα εκτυπώνει <code> obj1 instanceof Parent: true obj1 instanceof Child: false obj1 instanceof MyInterface: false obj2 instanceof Parent: true obj2 instanceof Child: true obj2 instanceof MyInterface: true </code> |Προηγούμενο: [[ :java:abstract_classes_vs_interfaces | Συγκρίνοντας Abstract Κλάσεις και Interfaces ]] | [[:toc|Περιεχόμενα]] | Επόμενο: [[ :java:nested_classes | Εμφωλευμένες Κλάσεις ]]|

java/instanceof.1554485542.txt.gz · Last modified: 2019/04/05 17:32 by gthanos