There are three major features of object-oriented: encapsulation, inheritance, and polymorphism. From a certain perspective, encapsulation and inheritance are almost all prepared for polymorphism. This is our last concept and the most important knowledge point.
1. Definition:
Polymorphism: refers to allowing objects of different types to respond to the same message. That is, the same message can adopt a variety of different behaviors according to the different objects sent. (Sending a message is a function call)
2. The technology to implement polymorphism is called: dynamic binding, which refers to judging the actual type of the referenced object during execution and calling its corresponding method according to its actual type.
3. Function: eliminate the coupling relationship between types.
4. In reality, there are countless examples of polymorphism. For example, pressing the F1 key, if the AS3 help document is currently popped up under the Flash interface; if the Word help is currently popped up under the Word; if the Windows help is currently popped up under the Windows help and support. The same event occurs on different objects and produces different results.
5. Below are three necessary conditions for polymorphic existence, which require everyone to memorize it when dreaming!
Three necessary conditions for polymorphism
1. There must be inheritance;
2. There must be rewrite;
3. The parent class reference points to the child class object.
6. Benefits of polymorphism:
1) Substitutability: Polymorphism has interchangeability for existing code. For example, polymorphism works on the circle Circle class, and also works on any other circular geometry, such as a circle.
2) Extensibility: Polymorphism is extensible to the code. Adding new subclasses does not affect the operation and operation of existing classes' polymorphisms, inheritance, and other characteristics. In fact, it is easier to obtain polymorphic functions by adding new subclasses. For example, on the basis of realizing the polymorphism of cones, semicones and hemispheres, it is easy to add polymorphisms of spheres.
3) Interface-ability: Polymorphism is achieved by superclasses through method signatures, providing a common interface to subclasses, and subclasses are implemented by improving or overwriting them. As shown in Figure 8.3. In the figure, the super class Shape specifies two interface methods that implement polymorphism, computeArea() and computeVolume(). Subclasses, such as Circle and Sphere, improve or override these two interface methods in order to achieve polymorphism.
4) Flexibility: It reflects flexible and diverse operations in the application and improves usage efficiency.
5) Simplicity: Polymorphism simplifies the code writing and modification process of application software, especially when dealing with operations and operations of a large number of objects, this feature is particularly prominent and important.
Cat and dog case code
class Animal {public void eat(){System.out.println("eat");}public void sleep(){System.out.println("sleep");}}class Dog extends Animal {public void eat(){System.out.println("Dog eat meat");}public void sleep(){System.out.println("Dog sleeps");}}class Cat extends Animal {public void eat(){System.out.println("Cat eats fish");}public void sleep() {System.out.println("Cat sleeps on its tummy");}}class Pig extends Animal {public void eat() {System.out.println("Pig eats cabbage");}public void sleep() {System.out.println("Pig sleeps on its side");}}//Tool class for animal operations class AnimalTool {private AnimalTool(){}/* //Calling cat's function public static void useCat(Cat c) { c.eat(); c.sleep(); } //Calling dog's function public static void useDog(Dog d) { d.eat(); d.sleep(); } //Calling pig's function public static void usePig(Pig p) { p.eat(); p.sleep(); } */public static void useAnimal(Animal a) {a.eat();a.sleep();}//Class all possibilities into animals}class DuoTaiDemo2 {public static void main(String[] args) {//I like cats, so I have a Cat c = new Cat();c.eat();c.sleep();//I like cats very much, so I have another Cat c2 = new Cat();c2.eat();c2.sleep();//I like cats in particular and have another Cat c3 = new Cat();c3.eat();c3.sleep();//...System.out.println("------------------------");//The problem is, I have raised a lot of cats, and it is acceptable to create an object every time // But what about? Calling the method, don't you think it's very similar? It's just that the object names are different. //We are planning to use methods to improve //Invoke method to improve version //useCat(c);//useCat(c2);//useCat(c3);//AnimalTool.useCat(c);//AnimalTool.useCat(c2);//AnimalTool.useCat(c2);//AnimalTool.useCat(c3);AnimalTool.useAnimal(c2);AnimalTool.useAnimal(c2);AnimalTool.useAnimal(c3);System.out.println("------------------------");//I like dogs Dog d = new Dog();Dog d2 = new Dog();Dog d3 = new Dog();//AnimalTool.useDog(d);//AnimalTool.useDog(d2);//AnimalTool.useDog(d3);AnimalTool.useAnimal(d);AnimalTool.useAnimal(d2);AnimalTool.useAnimal(d2);AnimalTool.useAnimal(d3);System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Pig();//AnimalTool.usePig(p);//AnimalTool.usePig(p2);//AnimalTool.usePig(p3);AnimalTool.useAnimal(p2);AnimalTool.useAnimal(p2);AnimalTool.useAnimal(p3);System.out.println("-------------------------------");//I like pet wolf, tiger, leopard...//Define the corresponding class, inherit the animal, provide corresponding method rewrite, and add method calls to the tool class //The first few must be written, I have no objection // However, the tool class is changed every time, please don't worry //I just thought, can you not change it // Too simple: write all the animals on. The question is what is the name? Which ones need to be added? // Use another solution instead. }/* //Calling cat's function public static void useCat(Cat c) { c.eat(); c.sleep(); } //Calling dog's function public static void useDog(Dog d) { d.eat(); d.sleep(); } */}7. Implementation method of polymorphism in Java: interface implementation, inheriting the parent class for method rewriting, and overloading methods in the same class.
8. Classification of polymorphisms in Java:
In Java, polymorphisms can be roughly divided into the following situations:
1) Person is the parent class and student is the child class. Then: personp=newstudent();
2) Fliable is an interface and bird is a class that implements the interface, so: fliablef=newbird();
3) Fliable is an abstract class, bird is a class that inherits fliable, so: fliablef=newbird();
When polymorphism, it is necessary to state that p declares as a reference to the parent class, but it is actually a reference to the child class. But he can only call methods in the parent class. If the method in the subclass overrides the parent class method, the parent class method (virtual method call) will be called. The same is true for interface polymorphism. Maybe you will ask, if f wants to call its own method, wouldn’t that make a mistake? In fact, this is also a method coverage, because the subclass implementing the interface will definitely implement the methods in the interface, so in this case the method in bird is called. But if bird has a method that is not defined in the interface, then f cannot be called.
9.instanceof operator:
The polymorphic mechanism of the Java language causes the declaration type of the reference variable to be inconsistent with the type of the actual reference object. Combined with the virtual method calling rules, we can conclude that two reference variables declared as the same type may also have different behaviors when calling the same method. The instanceof operator is introduced here.
So if I declare personp=newstudent(); can I convert p to student? Of course, it can be done, but it has to be forced (the son wants to be a father and he will come directly, but if the father wants to be a son, he will be forced).
Usually, instanceof is added when casting.
if(pinstanceofstudent){students=(student)p;}
Polymorphism runs through the entire Java learning. For example, when writing catch statements when handling exceptions, we stipulate that subclass exceptions must be written in the front and parent class exceptions must be written in the back. Why? The reason is polymorphism. Our catch statement format: catch (Exceptione). When an exception is generated, a java program will automatically generate an exception object. If a child class exception is generated first and the parent class exception is written in front, this catch statement will definitely be executed according to the polymorphism, and it will jump out after executing a catch statement.
10. Example:
Although I don’t understand JAVA’s polymorphism very well, the following example makes me understand some:
class A{public String show(D obj)..{return ("A and D");}public String show(A obj)..{return ("A and A");}}class B extends A{public String show(B obj)..{return ("B and B");}public String show(A obj)..{return ("B and A");}}class C extends B{}class D extends B{}class E{public static void main(String [] args) {A a1 = new A();A a2 = new B();B b = new B();C c = new C();D d = new D();System.out.println(a1.show(b));//①System.out.println(a1.show(c));//②System.out.println(a1.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));//⑨}}(III) Answer
① A and A ② A and A ③ A and D ④ B and A ⑤ B and A ⑥ A and D ⑦ B and B ⑧ B and B ⑨ A and D
**** There is a good person's answer****
There are two key points to this problem:
One is the relationship between the subclass and the parent class, and the other is the issue of calling overloaded methods.
Subclass objects can be used directly as parent objects, but otherwise, they cannot. For example, people are the parent class and students are the subclass of people, so student objects must have the attributes of human objects, but human objects may not necessarily have the characteristics of student objects. Therefore, student objects can be used as human objects, but human objects cannot be used as student objects. Note that when using the subclass object as a parent object, the subclass object will lose all subclass characteristics and only retain attributes and methods with the same name as the parent class (the same name method is not only the same function name, but also the parameter type must be the same, otherwise it will not be retained).
If an overloaded method is defined in a class, the system will automatically select and call the appropriate method according to the type of the parameter when calling the method.
1) a1.shows(b), there is no method containing class B parameters in A, but a method containing class A parameters is called according to the principle that the parent class of the subclass object is available, so the method is called.
publicStringshow(Aobj)...{return("AandA");}
2) a1.show(c), Class C is a subclass of Class B, and Class B is a subclass of Class A, so Class C objects can be used as a class A object. The result is the same as above.
3) a1.show(d), directly call the method in A according to the parameter type
publicStringshow(Dobj)...{
return("AandD");}
4) a2.show(b), a2 was originally a B object, but it was assigned to class A variable, so a2 only retains properties and methods with the same name as parent class A. a2.show(b) calls the reserved method in class B with the same name as the parent class and the same parameter as the parent class
public String show(A obj)...{
return ("B and A");
}
5) a2.show(c), the reserved method of Class B does not have Class C parameter methods, but there are parameter methods of parent class B that contains C, so the method called
public String show(A obj)...{
return ("B and A");
}
I think this explanation is more reasonable: a2 was originally an object of class B, but the value was assigned to class A, C is a subclass of B, and B is a subclass of A, so a2 retains the properties and methods in class B with the same name as A.
6) a2.show(d), the call is from Class A
public String show(D obj)...{
return ("A and D");
}
7) b.show(b), call the
public String show(B obj)...{
return ("B and B");
}
8) b.show(c), there is no method with C parameter in class B, but there is a method with B parameter, so the method is called
public String show(B obj)...{
return ("B and B");
}
9) b.show(d), explanation is the same as 8
Summarize
The above is the entire content of this article’s summary of Java polymorphism, and I hope it will be helpful to everyone. If you have any questions, please leave a message at any time and look forward to your valuable comments!