Java Object-oriented---polymorphism

Source: Internet
Author: User

The manifestation of polymorphism

1. Overloading and rewriting of methods

2, the polymorphism of the object

The polymorphism of the object

Upward transformation

The program will automatically complete

Parent class Parent Class object = Child class instance

Down transformation

Forced type conversion ( downward transformation must first be shifted upward, then downward )

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

Eg:a a=new b;b b= (B) A;

The use of polymorphism

A simple example:

classA { Public voidTell () {}}classBextendsA { Public voidtellb () {}}classCextendsA { Public voidTELLC () {}} Public classDemo { Public Static voidMain (String args[]) {Say (NewB ()); Say (NewC ()); } Public voidsay (a a) {A.tell (); }}

Note: If you do not use polymorphism, you need to overload the say method, and there are several object calls that need to be overloaded several times. In this case, the more redundant code is generated. The demo code is as follows:

 Public class demo{
   Public Static void    Main (String args[]) {Say (new B ());  Say (new C ());  } publicvoid say (b b) {B.tell ();  } publicvoid say (c c) {C.tell (); }}

instanceof Keywords

Role

Determines whether an instance is an object of a class and returns a Boolean

The sample code is as follows:

Newinstanceofinstanceof newinstanceof    instanceof B); execution Result: True false True True   

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.