polymorphic
1. Concept
Polymorphism is an important feature of object-oriented programming (OOP). It refers to that the same entity has multiple forms at the same time, that is, the same object represents different objects at different times. It refers to multiple forms of objects.
Different subclass objects can be regarded as parent classes, so as to shield the differences between different subclass objects, write general code, make general programming and unify call standards.
For example, your female pot friend asks you to buy some fruit, whether it's apple or watermelon, as long as it's fruit, which is the embodiment of polymorphism in life
For example, kittens, puppies and pigs can be summarized as small animals. Each small animal needs to eat, so we can uniformly set that they must eat. However, the habits of each small animal are different, so this can be set as a special function of the small animal. Polymorphic objects can only call the functions rewritten in the subclass defined in the parent class, It cannot call the special functions of subclasses, which realizes the unification of code
2 . characteristic
- The premise of polymorphism 1: inheritance
- The premise of polymorphism 2: there should be rewriting of methods
- The parent class reference points to the child class object, such as: Animal a = new Cat();
- In polymorphism, compile to the left and run to the right
3. Exercise: introduction to polymorphism
Create package: CN tedu. oop
Create class: testdemo java
package cn.tedu.oop2; /*This class is used as an introduction to polymorphism*/ public class TestDemo { public static void main(String[] args) { //6. Create "pure" objects for testing Animal a = new Animal(); Cat c = new Cat(); Dog d = new Dog(); a.eat();//Little Animal can eat anything ~ it calls the function of the parent class itself c.eat();//Kittens like to eat dried fish ~ what they call is the function rewritten by subclasses d.eat();//Dogs love meat and bones ~ what they call is the function rewritten by subclasses /*2.Parent objects cannot use the unique functions of child classes*/ //a.jump();// An error is reported. There is no such method in the Animal class //a.run();// An error is reported. There is no such method in the Animal class c.jump();//Kitten Cat jumps high ~, and subclasses can call their own functions d.run();//Dog dog runs fast ~, and subclasses can call their own functions //7. Create polymorphic objects for testing /*3.Pithy formula 1: parent class reference points to child class object * Explanation: the address value of the created subclass object is saved by the reference type variable of the parent type*/ Animal a2 = new Cat();//The address value of Cat class object is given to the parent type variable a2 to save Animal a3 = new Dog();//The address value of the Dog class object is given to the parent type variable a3 to save //8. Test polymorphic objects /*4.Pithy formula 2: compile to the left, run to the right * To interpret this object as a polymorphic parent class, you must compile it as a polymorphic parent class * This method must be overridden in subclasses to meet polymorphism. Subclasses actually work*/ a2.eat();//Kittens like to eat dried fish ~, and polymorphic objects use the definition of the parent class and the method body of the child class } } /*1.The premise of polymorphism: inheritance + rewriting*/ //1. Create parent class class Animal{ //3. Common method of creating parent class public void eat(){ System.out.println("Small animals Animal You can eat anything~"); } } //2.1 create subclass 1 class Cat extends Animal{ //4.1 method of adding and rewriting public void eat(){ System.out.println("Kittens love dried fish~"); } //5.1 add special functions of subclasses public void jump(){ System.out.println("kitten Cat Jump high~"); } } //2.2 create subclass 2 class Dog extends Animal{ //4.2 method of adding and rewriting @Override public void eat(){ System.out.println("Dogs love meat and bones~"); } //5.2 add special functions of subclasses public void run(){ System.out.println("puppy Dog Run fast~"); } }
4. Benefits of polymorphism
- Polymorphism allows us to use some methods of an object without paying attention to its specific type
- It improves the scalability and maintainability of the program
5. Use of polymorphism
Premise: polymorphic objects see themselves as parent types
- Member variable: uses the of the parent class
- Member method: subclass method is used due to rewriting
- Static member: it is loaded with the loading of the class. Whoever invokes it will return the name of who
6. Exercise: polymorphic member usage test
Create package: CN tedu. oop
Create class: testdemo2 java
package cn.tedu.oop2; /*This class is used to test the usage of polymorphic members*/ public class TestDemo2 { public static void main(String[] args) { //7. Create pure subclass objects Dog2 d = new Dog2(); System.out.println(d.sum);//20. Subclass's own attributes d.eat();//Puppies love to eat meat buns. They have their own way //8. Create polymorphic objects /*Pithy formula 1: parent class reference points to child class object*/ /*Pithy formula 2: compile (save) to the left and run (effect) to the right*/ Animal2 a = new Dog2(); /*In polymorphism, the member variable uses the of the parent class*/ System.out.println(a.sum);//10 /*In polymorphism, the method declaration uses the parent class, and the method body uses the child class*/ a.eat();//Dogs love meat buns /*In polymorphism, the static method of calling is a parent class, because polymorphic objects regard themselves as parent classes. * Use the static resources in the parent class directly*/ a.play();//No hint, you can play anything~ Animal2.play(); } } //1. Create parent class class Animal2{ //3. Create a member variable of the parent class int sum = 10; //4. Common method of creating parent class public void eat(){ System.out.println("You can eat anything~"); } //9.1 define the static method play of the parent class public static void play(){ System.out.println("Play anything~"); } } //2. Create subclasses class Dog2 extends Animal2{ //5. Define member variables of subclasses int sum = 20; //6. Override the method of the parent class @Override public void eat(){ System.out.println("Dogs love meat buns"); } //9.2 create static method play of subclass //@Override /*As like as two peas, there are two static methods that appear exactly in the two classes. * Static methods belong to class resources. There is only one copy, and there is no rewriting * In which class is defined, it is used as the resource of which class*/ public static void play(){ System.out.println("Dogs like to play ball games~"); } }
7 expansion
7.1 comprehensive case of automobile design
Create package: CN tedu. oopexec
Create class: designcar java
package cn.tedu.oop2; /*This class is used to complete automobile design cases*/ public class DesignCar { public static void main(String[] args) { //9. Create a pure parent object for testing Car c = new Car(); System.out.println(c.getColor());//null c.start(); c.stop(); //c.swim();// An error is reported. The parent object cannot call the special function of the child class //10. Create pure subclass objects for testing BMW b = new BMW(); System.out.println(b.color);//Colorful black System.out.println(b.getColor());//null b.start();//Get out of the way. My car is taking off~ b.stop();//Oh, my God, the fire is out~ //11. Create polymorphic objects for testing Car c2 = new TSL(); //System.out.println(c2.color); System.out.println(c2.getColor()); c2.stop(); c2.start(); //c2.swim(); } } //1. Through analysis, an automobile class is abstracted class Car{ //2. Define and encapsulate the attribute of automobile class -- member variable private String brand;//brand private String color;//colour private int id;//number private double price;//Price //3. Define functions public void start(){ System.out.println("My car has started~"); } public void stop(){ System.out.println("Oh, my God, the fire is out~"); } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } //4. Create subclasses class BMW extends Car{ String color = "Colorful black"; //5. Override the method of the parent class @Override public void start(){ System.out.println("Get out of the way. My car is taking off~"); } } //6. Create subclass 2 class TSL extends Car{ //7. Override the method of the parent class @Override public void stop(){ System.out.println("Oh, mom, why can't you stop"); } //8. Add special functions of subclasses public void swim(){ System.out.println("Unexpectedly, I'm still a submarine"); } }
7.2 unified calling standard
package cn.tedu.oop2; public class TestFruit { public static void main(String[] args) { Fruit f = new Fruit(); Apple a = new Apple(); Orange o = new Orange(); get(f); get(a); get(o); } //Just create a method and you can perform very different effects //Ignore the differences of subclass objects and treat them as parent types public static void get(Fruit f){ f.clean(); } } class Fruit{ public void clean(){ System.out.println("Wash the fruit before eating"); } } class Apple extends Fruit{ @Override public void clean(){ System.out.println("Apples need peeling"); } } class Orange extends Fruit{ @Override public void clean(){ System.out.println("Oranges need peeling"); } }
7.3 differences between static variables and instance variables
The difference in syntax definition: static keyword should be added before static variable, but not before instance variable.
The difference in program running time: the instance variable belongs to the attribute of an object. The instance object must be created before the instance variable can be allocated space and used. Static variables do not belong to an instance object, but to a class, so they are also called class variables. As long as the program loads the bytecode of the class without creating any instance object, the static variables will be allocated space and can be used. In short, instance variables can only be used through this object after creating an object, while static variables can be directly referenced by class names.
7.4 upward and downward transformation
In JAVA, inheritance is an important feature. Through the extends keyword, subclasses can reuse the functions of the parent class. If the parent class cannot meet the needs of the current subclass, the subclass can override the methods in the parent class to extend.
Then there are polymorphic applications in this process. There are two ways of transformation: upward transformation and downward transformation.
Upward Transformation: different subclass objects can be regarded as parent classes, so as to shield the differences between different subclass objects, write general code, make general programming and unify call standards.
For example: Parent and Child
The reference of the parent class points to the child class object: Parent p=new Child();
Note: during upward transformation, the subclass object is regarded as the parent object and can only call the functions of the parent class. If the subclass overrides the methods declared in the parent class, the method body executes the functions after the subclass is repeated. However, at this time, the object regards itself as the parent type, so other resources still use the parent type.
For example, Hua Mulan joined the army for her father. Everyone regarded Hua Mulan as her father, but Hua Mulan actually joined the army. Moreover, Hua Mulan can only do what her father can do, and she can't make up in the military camp.
Downward transformation (less): the reference of the subclass points to the subclass object, and the forced transformation must be taken in the process. This is a subclass object that has been modeled upward before. You still want to perform the unique functions of the subclass, so you need to restore it to a subclass object
Parent p = new Child();// In this case, P is the parent type
Child c = (Child)p;// At this time, the P of the Parent type is converted to the small type child
In fact, it is equivalent to creating a subclass object. You can use the parent class or your own
Note: the purpose of downward transformation is to facilitate the use of special methods of subclasses, that is, when the subclass methods are expanded, the subclass functions can be used directly.
For example, after the war, Hua Mulan doesn't need to be regarded as her father anymore, so she can "stick yellow on the mirror"