Polymorphic upward transformation and downward transformation 2016.12.8

Source: Internet
Author: User
Tags export class

As we all know, the override of a method is a polymorphic representation of the derived class and the base class, which can be transformed upward into a base class when instantiated, but the disadvantage is that the upward transformation can only implement the methods defined in the base class, but these methods are enriched in the export class.

In reality, we also need to extend the methods that are not in the base class in the export class, which is used when the instantiation is turned down to implement the extended method of the exported class.

The following examples illustrate:

Parent class Cycle Class:

 Package Cn.qdu.transport; class Cycle {    publicvoid  Ride () {        System.out.println ("Ride Cycle");    }          Public String wheels (string name,int  i) {        System.out.println (name+ "This means of transport has" +i+ "Wheels")        ; return name;}            }

Subclass Unicycle Class: Not only overrides the parent class ride () method, but also expands the new functionality, adds a new method balance ()

 Package Cn.qdu.transport; class extends Cycle {
@Override publicvoid Ride () { System.out.println ("Ride unicycle.") ); } Public void balance () { System.out.println ("unicycle balance");} }

Main function:

 Package Cn.qdu.transport;  Public class Test {    publicstaticvoid  main (string[] args) {        Cycle unicycle= New unicycle ();//Upward Transformation                cycle.ride ();        Cycle.wheels ("cycle", 2);                        Unicycle.ride ();        Unicycle.wheels ("Unicycle", 1);        ((Unicycle) unicycle). balance ();//Downward Transformation

Operation Result:

Ride Cyclecycle This kind of vehicle has 2 wheels ride unicycle.unicycle This means of transport has 1 wheels unicycle balance

Polymorphic upward transformation and downward transformation 2016.12.8

Related Article

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.