A further understanding of the Java instanceof keyword _java

Source: Internet
Author: User

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:

Copy Code code as follows:

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:

Copy Code code as follows:

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:

Copy Code code as follows:

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:

Copy Code code as follows:

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

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.