A bug occurs when a Java object reference is null

Source: Internet
Author: User

In Java, objects tend to contain properties, methods, and a storage space, which can be considered an empty object if the properties and methods of an object are empty.

An empty object is also an object, referencing a method or property by its object name, but a little different from a generic object.

1. Null pointer exceptions occur when a non-static method is called by an empty object, such as:

This is because a null object within its own storage space is free of any methods and properties, so any empty object. XXX calls a non-static method or property and a null pointer exception occurs;

But an empty object can call a static method or property, as follows:

This is because the static method is stored in a static pool, and all objects of a class share a static pool method;

In addition, we can understand null as an object of the null type, and when necessary, he can cast to any type of object except for attributes and methods.

The following is an example of a null call to a static property and method:

After removing the property and the keyword static in front of the method, the program does not report an error (stating that instantiating NULL is a null pointer object is not a problem), but the runtime will provide a null pointer exception (stating that there are no methods and properties in the instantiated space), such as:

The above procedure can be roughly used to describe the static methods of each class:

The following is a reference method procedure for some non-empty objects, similar in structure to the above, but ...

1. Non-null object is coerced into non-parent object, program error, such as:

2. Non-empty objects can be converted to parent class objects, but it does not make much sense to feel like digging a hole because the results of their operation before and after conversion are no different, such as:

The result of the operation is the same:

Reproduced from CSDN original article

A bug occurs when a Java object reference is null

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.