1. Substitutability. Polymorphism can replace existing code. For example, polymorphism applies to the Circle class, and also to any other circular geometry, such as rings.
2. Extensibility. Polymorphism can be extended to code. Adding new subclasses does not affect the polymorphism, inheritance and other characteristics of existing classes. In fact, it is easier to get polymorphic functions by adding subclasses. For example, on the basis of realizing the polymorphism of cone, semi-cone and semi-sphere, it is easy to increase the polymorphism of sphere.
3. Interface ability. Polymorphism is realized by superclass providing * * * interface to subclass through method signature, and method signature is perfected or covered by subclass. As shown in Figure 8.3. The superclass shape in the figure specifies two interface methods to realize polymorphism, computeArea () and computeVolume (). Subclasses, such as Circle and Sphere, improve or cover these two interface methods in order to realize polymorphism.
4. Flexibility. Flexible and diverse operations are reflected in the application, and the use efficiency is improved.
5. simple. In the process of coding and modifying application software, especially when dealing with the operation and operation of a large number of objects, polymorphic simplification is particularly prominent and important.
The realization of polymorphism in Java: interface realization, method rewriting of inheriting parent class, method overloading in the same class.
The following is a small example showing the use of polymorphism:
Level a
Common string display (dobj)
Return ("A and d ");
}
Common string show (aobj) (
Return ("A and a ");
}
}
Class b extends A{
Common string display (b object) (
return(“B and B”);
}
Common string show (aobj) (
Return ("B and a ");
}
}
Class c extends B{}
Class d extends B{}
What is the following output?
A a 1 = new a ();
a a2 = new B();
B B = new B();
C C = new C();
D D = new D();
system . out . println(a 1 . show(b)); ①
system . out . println(a 1 . show(c)); ②
system . out . println(a 1 . show(d)); ③
system . out . println(a2 . show(b)); ④
system . out . println(a2 . show(c)); ⑤
system . out . println(a2 . show(d)); ⑥
system . out . println(b . show(b)); ⑦
system . out . println(b . show(c)); ⑧
system . out . println(b . show(d)); ⑨
Answer:
① A and a
② A and a
③ A and d
④ B and a
⑤ B and a
6 a and d
⑦ B and B
⑧ B and B
Pet-name ruby a and d