s2/java/03-polymorphism

Source: Internet
Author: User

Polymorphic: The same implementation interface that uses different examples to perform different operations.

Rules when a subclass is converted to a parent class:

A reference to a parent class is directed to a subclass object, called upward transformation (upcasting), for automatic type conversion.

The method that is called by the parent class reference variable is the child class that overrides or inherits the parent class's method, not the parent class.

A method that is unique to a subclass cannot be called by referring to a variable through the parent class.

Three conditions to achieve polymorphism:

The existence of inheritance (inheritance is the basis of polymorphism, there is no polymorphism without inheritance).

Subclasses override the method of the parent class (the method is called after the subclass is overridden by polymorphism).

The parent class refers to a variable that points to a subclass object (such as a type conversion to a parent class).

When the upward transformation occurs, the method that is unique to the subclass cannot be called. However, you can do this by converting the parent class to a subclass when you need to invoke a method that is unique to the child class.

Assigns a reference to a subclass object to a parent class reference, called a downward transformation, which must be cast at this time.

instanceof operator

Syntax: Object instanceof class or interface

This operator is used to determine whether an object belongs to a class or implements an interface with the result of true or false.

When using the instanceof operator, the object must be of the same type as the class or interface specified by the second parameter of Instanceof, or a compilation error will occur. For example, a compilation error occurs for a pet instanceof String.

Instanceof is typically used in conjunction with coercion type conversions.

s2/java/03-polymorphism

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.