A summary of the polymorphism of Java's three characteristics

  • 2020-11-18 06:16:01
  • OfStack

Three features of object orientation: encapsulation, inheritance and polymorphism. From a definite point of view, encapsulation and inheritance are almost always polymorphic. This is our last concept and the most important knowledge point.

1. Definition:

Polymorphism: Allows objects of different classes to respond to the same 1 message. That is, the same 1 message can behave in many different ways depending on the object it is sent to. (Sending a message is a function call)

2. The technique for implementing polymorphism is called dynamic binding (dynamicbinding), which means that during execution, the actual type of the referenced object is determined and the corresponding method is called according to its actual type.

3. Role: To eliminate coupling between types.

4. In reality, the examples of polymorphism are too numerous to mention. For example, if you press the F1 key, what pops up in the Flash interface is the help document of AS3. If it is currently under Word it is Word help; What pops up under Windows is Windows Help and support. The same event on different objects will produce different results.

5. Here are the three essential conditions for polymorphic existence, which require you to recite them in your dreams!

Three necessary conditions for polymorphic existence

1. Inheritance;

2. Rewrite;

3. Superclass references refer to subclass objects.

6. Advantages of polymorphism:

1) Replaceability (substitutability) : Polymorphism is replaceable for existing code. For example, polymorphic works for the Circle class of circles, as well as for any other circular geometry, such as circles.

2) Extensibility (extensibility) : Polymorphism has extensibility for code. Adding new subclasses does not affect the polymorphism, inheritance, or other features of existing classes. It's actually easier to get polymorphic functionality with new subclasses. For example, on the basis of realizing the polymorphic of cone, hemicycle and hemicycle, it is easy to add the polymorphism of sphere class.

3) Interfacability (ES40en-ability) : Polymorphism is achieved by the superclass providing a common interface to the subclass through method signature, which is perfected or overwritten by the subclass. See Figure 8.3. The superclass Shape in the figure specifies two interface methods to implement polymorphism, computeArea() and computeVolume(). Subclasses, such as Circle and Sphere, refine or override these two interface methods in order to implement polymorphism.

4) Flexibility (flexibility) : It reflects flexible and diverse operations in the application, and improves the use efficiency.

5) Simplification (simplicity) : Polymorphic simplification of the coding and modification process of application software, especially when dealing with computation and operation 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(" The dog meat ");
	}
	public void sleep(){
		System.out.println(" The dog sleeps standing up ");
	}
}
class Cat extends Animal {
	public void eat() {
		System.out.println(" The cat eat the fish ");
	}
	public void sleep() {
		System.out.println(" A cat sleeps on its stomach ");
	}
}
class Pig extends Animal {
	public void eat() {
		System.out.println(" Pigs eat cabbage ");
	}
	public void sleep() {
		System.out.println(" The pig sleep by side ");
	}
}
// Tool classes for animal manipulation 
class AnimalTool {
	private AnimalTool(){
	}
	/*
  // Call the cat's function 
  public static void useCat(Cat c) {
    c.eat();
    c.sleep();
  }
  // Call the dog function 
  public static void useDog(Dog d) {
    d.eat();
    d.sleep();
  }
  // Call the pig function 
  public static void usePig(Pig p) {
    p.eat();
    p.sleep();
  }
  */
	public static void useAnimal(Animal a) {
		a.eat();
		a.sleep();
	}
	// Classify all possibilities as animals 
}
class DuoTaiDemo2 {
	public static void main(String[] args) {
		// I like cats, so I keep them 1 only 
		Cat c = new Cat();
		c.eat();
		c.sleep();
		// I like cats very much, so I keep them again 1 only 
		Cat c2 = new Cat();
		c2.eat();
		c2.sleep();
		// I like cats so much that I have them again 1 only 
		Cat c3 = new Cat();
		c3.eat();
		c3.sleep();
		//...
		System.out.println("--------------");
		// The question , I have a lot of cats and it's acceptable to create objects every time 
		// But? ? Call a method, don't you think it's similar ? Just the object name no 1 The sample. 
		// We are going to improve it in ways 
		// Improved version of invocation style 
		//useCat(c);
		//useCat(c2);
		//useCat(c3);
		//AnimalTool.useCat(c);
		//AnimalTool.useCat(c2);
		//AnimalTool.useCat(c3);
		AnimalTool.useAnimal(c);
		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(d3);
		System.out.println("--------------");
		// I like pet pigs 
		// define 1 A pig class, which inherits from the animal, provides two methods, and has to add method calls of that class to the utility class 
		Pig p = new Pig();
		Pig p2 = new Pig();
		Pig p3 = new Pig();
		//AnimalTool.usePig(p);
		//AnimalTool.usePig(p2);
		//AnimalTool.usePig(p3);
		AnimalTool.useAnimal(p);
		AnimalTool.useAnimal(p2);
		AnimalTool.useAnimal(p3);
		System.out.println("--------------");
		// I like pet wolves, tigers, leopards ...
		// Define corresponding classes, inherit from animals, provide corresponding method overrides, and add method calls to tool classes 
		// I have no objection to writing the first few 
		// However, the utility class changes every time 
		// I was like, can't you just quit 
		// Too simple: Write all the animals. The question is what is the name ? Which ones need to be added ?
		// To switch to another 1 Plant a solution. 
	}
	/*
  // Call the cat's function 
  public static void useCat(Cat c) {
    c.eat();
    c.sleep();
  }
  // Call the dog function 
  public static void useDog(Dog d) {
    d.eat();
    d.sleep();
  }
  */
}

7. Implementation of polymorphism in Java: interface implementation, method rewriting by inheriting the parent class, method overloading in the same class.

8. Classification of polymorphism in Java:

In java, polymorphism can be roughly divided into the following cases:

1)person is the parent class and student is the subclass. Then: personp=newstudent();

2)fliable is the interface, and bird is the class that implements the interface, then: fliablef=newbird();

3)fliable is an abstract class, and bird is a class inherited from fliable, then: fliablef=newbird();

Polymorphic requires that p be declared 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 a superclass method is overridden by a method in a subclass, the superclass method (virtual method call) is called. The same goes for interface polymorphism, you might ask, if f were to call its own method, wouldn't that be an error? This is also method override, because the subclass that implements the interface will certainly implement the method in the interface, so the method in bird is invoked in this case. But if bird has 1 method that is not defined in the interface, THEN f cannot be called.

9.instanceof operator:

The polymorphic mechanism of THE java language leads to the possibility that the declared type of a reference variable may not be the same as the type of the object it actually refers to. Combined with the virtual method invocation rules, it can be concluded that two reference variables declared of the same type may also behave differently when calling the same method. This is where the instanceof operator comes in.

So if I declare personp=newstudent (); Can I change p to student? Sure, but then there's the forced conversion.

instanceof is usually added to the cast.

if(pinstanceofstudent){students= (student) p; }

Polymorphism runs through the whole learning of java. For example, when catch is written in exception handling, we specify that subclass exceptions must be written before and superclass exceptions after. Why is that? The reason is polymorphism. Our catch statement format: catch (Exceptione). The java program will automatically generate an exception object when it produces an exception. If a subclass exception is generated first and the superclass exception is written in front of it, then the catch statement will be executed according to the polymorphism, and the catch statement will jump out after executing one.

10. Example:

Although I don't know much about the polymorphism of JAVA, the following example makes me understand some things:


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));
		// 1. 
		System.out.println(a1.show(c));
		// 2. 
		System.out.println(a1.show(d));
		// 3. 
		System.out.println(a2.show(b));
		// (4) 
		System.out.println(a2.show(c));
		// 5. 
		System.out.println(a2.show(d));
		//  6. 
		System.out.println(b.show(b));
		// All landowners 
		System.out.println(b.show(c));
		// today 
		System.out.println(b.show(d));
		// Pet-name ruby 
	}
}

(3) Answer


        1.   A and A
        2.   A and A
        3.   A and D
        (4)   B and A
        5.   B and A
        6.   A and D
        All landowners   B and B
        today   B and B
        Pet-name ruby   A and D

**** had a kind man's answer

There are two key points to this question:

1 is the relationship between a subclass and its parent, and 2 is the problem of calling overloaded methods.

Subclass objects can be used directly as superclass objects, but not vice versa. For example, human is a parent class and student is a subclass of human, so student object 1 must have the property of human object, but human object may not have the property of student object. Therefore, student objects can be used as human objects, but human objects cannot be used as student objects. Note that when a subclass object is used as a parent object, the subclass object loses all of its subclass properties and retains only the properties and methods of the same name as the parent (the method of the same name is not only the function name but also the parameter type, otherwise it will not be retained).

If an overloaded method is defined in a class, the system will automatically select the appropriate method to call when the method is called, based on the type of parameter.

1) a1.ES146en (b). In A, there is no method with B class parameter, but the method with A class parameter is called according to the principle that the parent class of the subclass object is available

publicStringshow(Aobj)...{return("AandA");}

2)a1.show(c), C class is a subclass of B class, and B class is a subclass of A class, so C class object can be used as A class object. Same as above.

3) a1.ES168en (d), which calls the method in A directly according to the parameter type

publicStringshow(Dobj)...{

return("AandD");}

4)a2.show(b), a2 is originally an B object, but it is assigned to the A class variable, so a2 only retains the properties and methods with the same name as the parent class A. a2.show (b) calls the same argument method reserved in the B class with the same name as the parent class

public String show(A obj)...{
return ("B and A");
}

5) a2.show(c), B class does not have the C class parameter method in the reserved method, but there is the parent class B parameter method containing C, so the method called
public String show(A obj)...{
return ("B and A");
}

I think this makes more sense: a2 is originally an object of class B, but assigns the value to class A, which is a subclass of B and B, which is a subclass of A, so a2 retains the properties and methods in class B that have the same name as A.

6) a2.show (d), called in the A class
public String show(D obj)...{
return ("A and D");
}

7) b. show(b), call in the B class

public String show(B obj)...{
return ("B and B");
}

8) b.show (c), B class has no method with C class parameter, but has a method with B class parameter, so call the method

public String show(B obj)...{
return ("B and B");
}

9) b.show(d), same as 8

conclusion

This is the summary of Java polymorphism in this paper, I hope to help you. Have what question to be able to leave a message at any time, look forward to your valuable opinion!


Related articles: