Java Polymorphism (caveats)

Source: Internet
Author: User

Polymorphism: A variable of the same type, when the same method is called, presents many different behavioral characteristics, which is polymorphic.

1. A reference variable can only invoke the method that its compile-time type has when it is compiled, but the runtime executes the method it has with the run-time type , so when writing Java code. A reference variable can only invoke methods contained in the class used to declare the variable, for example, by defining a variable P with the object p = new person () code, this p can only call methods of the object class, not the method defined in the person class.

2. Unlike methods, instance variables of an object are not polymorphic.

3. Forced conversions between reference variables

    • Conversions between base class types can only be performed between numeric types.
    • conversions between reference types can only be done between two types that have an inheritance relationship. Before forcing a type conversion, the instanceof operator is used to determine whether a successful conversion can be performed, thereby avoiding the classcastexcepetion exception. For example:
if instanceof String) {    = (String) objpri;}

instanceof operator Note: The compile-time type of the operand preceding the instanceof operator is either the same as the following class, or it has a parent-child inheritance relationship with the following class, or it causes a compilation error.

Java Polymorphism (caveats)

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.