Usage of instanceof keywords in Java

Source: Internet
Author: User
Tags inheritance reserved

Instanceof is a Java two-dollar operator, and ==,>,< is the same kind of stuff. Because it is made up of letters, it is also a reserved keyword in java. Its role is to test whether the object on its left is an instance of its right class, and returns a Boolean type of data. As an example:

String s = "I AM an object!";
Boolean IsObject = s instanceof Object;

We declare a String object reference, point to a String object, and then use INSTANCOF to test whether it points to an instance of the object class, which, obviously, is true, so return true, that is, the IsObject value is true.
Instanceof is of some use. For example, we wrote a billing system with three classes:

public class Bill {//omit details}
public class Phonebill extends Bill {//omit details}
public class Gasbill extends Bill {//omit details}

There is a method in the handler that accepts a bill type object and calculates the amount. Suppose the two bills are calculated differently, and the incoming Bill object may be either of two, so use instanceof to determine:

Public double Calculate (Bill Bill) {
if (Bill instanceof Phonebill) {
Calculate phone bills
}
if (Bill instanceof Gasbill) {
Calculate gas bill
}
...
}
This allows you to handle two of seed classes in one way.

However, this approach is often considered to be a failure to take advantage of the object-oriented polymorphism. In fact, the above features require method overload can be fully implemented, this is an object-oriented approach should be to avoid the return to structured programming mode. As long as two names and return values are the same, methods that accept different parameter types are available:

Public double Calculate (Phonebill bill) {
Calculate phone bills
}

Public double Calculate (Gasbill bill) {
Calculate gas bill
}


Examples are as follows:



Package com.instanceoftest;
Interface a{}
Class B implements a{

}
Class C extends B {

}

Class Instanceoftest {
public static void Main (string[] args) {
A A=null;
B B=null;
Boolean res;

System.out.println ("Instanceoftest test Case 1:------------------");
res = a instanceof A;
System.out.println ("A instanceof A:" + res);

res = b instanceof B;
System.out.println ("b instanceof B:" + res);

System.out.println ("\ninstanceoftest test Case 2:------------------");
A=new B ();
B=new B ();

res = a instanceof A;
System.out.println ("A instanceof A:" + res);

res = a instanceof B;
System.out.println ("A instanceof B:" + res);
res = b instanceof A;
System.out.println ("b instanceof A:" + res);

res = b instanceof B;
System.out.println ("b instanceof B:" + res);

System.out.println ("\ninstanceoftest test Case 3:------------------");
B b2= (c) new C ();

res = B2 instanceof A;
System.out.println ("B2 instanceof A:" + res);

res = B2 instanceof B;
System.out.println ("B2 instanceof B:" + res);

res = B2 instanceof C;
System.out.println ("B2 instanceof C:" + res);
}
}

/*
Result

Instanceoftest test Case 1:------------------
A instanceof A:false
b instanceof B:false
Instanceoftest test Case 2:------------------
A instanceof A:true
A instanceof B:true
b instanceof A:true
b instanceof B:true
Instanceoftest test Case 3:------------------
B2 instanceof A:true
B2 instanceof B:true
B2 instanceof C:true


Instanceof is a Java two-dollar operator, and ==,>,< is the same kind of stuff. Because it is made up of letters, it is also a reserved keyword in java. Its role is to test whether the object on its left is an instance of its right class, and returns a Boolean type of data.
Usage: An instance object instanceof a class name

Instanceof are typically used to invoke different methods based on different instances:

In a class that has an inheritance relationship, we can invoke different methods in different instances through polymorphism:

Example 1:

There are three classes, class names, and the relationships between them as follows

Animal (superclass) Dog (subclass) Cat (subclass)

You can draw the following objects

Animal Animal =new Animal (); = = "Animal instanceof animal return True

Dog dog=new Dog () = = = Dog instanceof Dog return True

Cat Cat=new cat () = = "Cat instanceof Cat Returns True

Animal dog=new Dog () = = = Dog Instanceof Animal return True

Animal cat=new cat () = = "Cat instanceof Animal return True


Animal dog=new Dog ();
Animal cat=new Cat ();
List List = new ArrayList ();

List.add (dog);
List.add (CAT);

Iterator it = List.iterator ();
while (It.hasnext ()) {
It.next (). Animaldo ();

}


Here we can rewrite the Animaldo method in animal in the dog and the Cat class by calling the Animaldo method and then automatically invoking methods in the same way based on different instances.
In a class that has no inheritance relationship, we can judge the current instance by instanceof and then invoke different methods according to different instances:

Example 2:


Station s = new station ();
Cell C = new cell ();

List List = new ArrayList ();

List.add (s);
List.add (c);


Iterator it = List.iterator ();
while (It.hasnext ()) {
Object obj = It.next ();
if (obj instanceof station) {
Station S1 = (station) obj;
S1.stationdo ();
}
if (obj instanceof Cell) {
Cell C1 = (cell) obj;
C1.celldo ();
}
}


Here we can judge the result by instanceof, execute the corresponding action method in the same way (Stationdo (), Celldo ()).
Generally in the use of no generic set (List, set, etc.), more use of instanceof, because the collection can save a variety of objects, so in the reading of the general to make corresponding judgments.

Therefore, the use of instanceof in most cases is not recommended practice, should make good use of polymorphism.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.