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