Understanding of Java Polymorphism

Source: Internet
Author: User

The three main features of object-oriented: encapsulation, inheritance, polymorphism, the most difficult to understand is polymorphic

Here is an example of a great God on the Internet:

1. Inheritance Relationship

Class a {         public string show (D  obj) {                return   ("A and d");         }             public string show (A obj) {                 return  ("A and a" );          }}class b extends a ... {         public string show (B obj) {                 return  ("B and  b ");         }          public string show (A&NBsp;obj) {                 return  ("B and a");          }}  class  c extends b {}   class d extends b {}

    2. Test

Public class test {    public static void main (String[]  args)  {        a a1 = new a ();         a a2 = new b ();         b b = new b ();         c c  = new c ();         d d = new d ();         system.out.println (A1.show (b));     //1         system.out.println (A1.show (c));     //2         system.out.println (A1.show (d));     //3         system.out.println (A2.show (b));     //4          system.out.println (A2.show (c));    //5         system.out.println (A2.show (d));    //6         system.out.println (B.show (b));    //7         system.out.println (B.show (c));    //8         system.out.println (B.show (d));     //9    }}

3. Output results

A and a//1a and a//2a and D//3b and a//4, which is to understand the focus B and a//5, which is to understand the focus of a and D//6b and B//7b and B//8a and D//9

4. Understanding

Class a{} class B extends a{} a = new B (); /* * 1. The result is a class A object, although actually passing in class B objects (UP) * 2. At this point a can only invoke methods in Class A, and cannot see the "unique" method in Class B * 3.     If there are some methods in the class A that are replicated in B, then a can be called by the method of the replication * * Image is a bit of B secretly changed some of the methods, at this time a does not know! */


Understanding of Java 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.