Java Object-oriented polymorphism

Source: Internet
Author: User

1, first or smooth the concept of the problem:

Polymorphism is the same method used in different objects when there are different interpretations, such as 9 o'clock on time to work, are working methods, but programmers are writing programs, finance in the point of money, HR in the release of ads.

2, said the concept of the use of the present and its advantages:

Before the use of polymorphism, the condition of polymorphism must be fulfilled: inheritance, encapsulation and upward transformation

So that we can understand the usefulness of inheritance, encapsulation, and so on for the use of polymorphism is also beneficial:

(1) To achieve a higher code readability,

(2) Improvement of code maintainability

(3) Improved Code extensibility

(4) The simplification of the code is also realized.

Here is an example of how polymorphic

Design a Ball

public class Ball {
String leixin = "Round";
private String name;

public String GetName () {
return name;
}

public void SetName ( String name {
this.name = name;
}
}

Ball games contain specific balls

Football

public class FootBall extends Ball {

}

Basketball

public class Lanball extends ball{
String leixin = "Leather";
}

Billiards

public class Taiball extends ball{

}

Designing a kid's class to play ball

public class Kids {
String name;
public void play (Ball b) {
SYSTEM.OUT.PRINTLN (name + "Play" +b.getname ());
Lanball L = (lanball) b;
System.out.println ("type" +l.leixin);
}
}

To test the kid's ball at last.

public class Testkids {
public static void Main (string[] args) {
Kids k = new Kids ();
K.name = "Xiao Ming";
Ball fb = new FootBall ();
Fb.setname ("football");
Ball lb = new Lanball ();
Lb.setname ("basketball");
K.play (FB);
}
}


This article is from the "Java" blog, so be sure to keep this source http://4534508.blog.51cto.com/4524508/1961889

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.