The embodiment and use of Java object-oriented-polymorphism

Source: Internet
Author: User

    1. Multi-State embodiment:

Overloading and overriding of methods

The polymorphism of the object


2. The polymorphism of the object:

Transition up: The program will automatically complete

Parent class Parent Class object = Child class instance

Down transformation: Forcing type conversions

Subclass sub-Class object = (subclass) Parent class instance

Class A{public void Tell01 () {System.out.println ("a--tell01");} public void Tell02 () {System.out.println ("a--tell02");}} Class B extends A{public void Tell01 () {System.out.println ("b--tell01");} public void Tell03 () {System.out.println ("b--tell03");}} public class PolDemo01 {public static void main (string[] args) {//upward transformation//b B = new B ();//a A = B;//a.tell01 ();//tell01 rewritten// A.TELL02 ();//downward transition A A = new B (); b b = (b) a;b.tell01 (); b.tell02 (); B.tell03 ();}}

Operation Result:

Upward transformation: down transformation:

B--tell01 b--tell01

A--tell02 a--tell02

B--tell03


3. Use of Object polymorphism:

Class A1{public void Tell01 () {System.out.println ("a--tell01");}} Class B1 extends A1{public void tell02 () {System.out.println ("b--tell02");}} Class C1 extends A1{public void Tell03 () {System.out.println ("c--tell03");}} Class D1 extends A1{}public class PolDemo02 {public static void main (string[] args) {Say (new B1 ()); Say (new C1 ()); Say (new D 1 ());} public static void Say (A1 a) {a.tell01 ();}}

Execution Result:

A--tell01

A--tell01

A--tell01


The embodiment and use of Java object-oriented-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.