Java language polymorphism

Source: Internet
Author: User

Https://www.ibm.com/developerworks/cn/java/java-language-polymorphism/index.html

Defining polymorphism

Polymorphism is a concept in object-oriented programming, meaning "different patterns", which actually means that the same method names behave differently depending on the object that implements the method.

In the context of the Java programming language, polymorphism means (through a method) that the same behavior contract is implemented in different ways for different objects. In Java, there are typically 3 ways to accomplish this:

    • Interface
    • Abstract methods
    • Method overrides

Polymorphism via interfaces

Essentially, the interface requires that each top-level object implementation be different (the top-level object refers to the first object in the inheritance graph, which explicitly declares that it implements the interface it refers to). Polymorphism is achieved when you pass object B that implements interface a by referencing interface a instead of referencing object B.

Using abstract methods to achieve polymorphism

The Java language can also create abstract methods that can exist only on abstract classes (that is, classes that cannot be instantiated). The idea of this approach is that you must implement the abstract method (defined on abstract class A) in a hierarchy somewhere in sub-class B (assumed to be foo ()) before you can instantiate B. Polymorphism is achieved when an object of type B is passed by referencing interface A.

Implementation of polymorphism by method rewriting

When subclass B provides an alternative implementation of a method in parent Class A (assuming Foo ()), it can be said that Foo () is rewritten. When an object of type B is passed as type A to a method, the Java runtime determines whether B.foo () must actually be called, rather than A.foo (). This is how polymorphism is achieved through method overrides.

Java language 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.