[Java] instanceof keyword

xiaoxiao2021-03-06  89

Java's instance keyword enables "Run-Time Type Identification, RTTI), that is, if it can determine if an object is not classically, there is no instance of a class, for example:

Class classa {classa () {}}

Class classb {classb () {}}

Public class myinstanceof {public static void main (string [] args) {Sayclass (new classa ()); signclass (new classb ());}

Public Static Void Sayclass (Object O) {IF (O InstanceOf Classa) System.out.Println ("this is classa"); if (o instanceof classb) System.out.println ("this is classb");}}

Output results:

This is classathis is classb

With the InstanceOf keyword, some differences in the Extened Class are implemented in the base class, and the code is streamlined and neat. But not abuse, in most cases we can achieve the same functionality through polymorphism .

转载请注明原文地址:https://www.9cbs.com/read-54121.html

New Post(0)