Last time I wrote down the important points in inheritance, and also to finish the topic of inheritance, today we are going to talk about another topic: polymorphism, which is one of the three object-oriented features and is a must for Learning Java.

Inheritance – Important Knowledge points

Learning tutorials recommended:

  • 1. Beijing High qi Java300 sets (Java strongly recommended) Java300 sets zero foundation for beginners video tutorial _Java300 sets zero foundation tutorial _Java beginners to learn the video foundation tutorial _Java language entry to master
  • Java from the beginning to master _/ Java basics/Arrays /OOP/ Collections /IO streams _
  • 3.Java common class basic combat 【 basic ramping 】Java common class combat basic tutorial _Java eight common class core foundation _Java common class basic /Java wrapper class /String class
  • Data structure and Algorithm (recommended) Data structure and algorithm _Java Data structure and Algorithm Foundation to Advanced /Java Basic Introduction to Advanced /Java Data structure analysis /Java Data structure FAQs _ bilibili_bilibili
  • 5.Java Object-oriented Programming _OOP basic In-depth introduction to Java object-oriented programming _OOP basic Dry goods sharing /JavaSE/ object-oriented programming /OOP programming
  • 6.GOF23 kinds of design patterns -23 design patterns in the course GOF23 kinds of design patterns explain _Java GOF23 kinds of design patterns explain the course _ from singleton to memo mode 23 kinds of patterns explain

Polymorphism is one of the three main characteristics of object orientation. The same behavior, through different subclasses, can be reflected in different forms.

Polymorphism refers to the same method call that may behave differently depending on the object. In real life, the implementation of the same method is completely different. For example: the same is to call people’s “rest” method, Zhang SAN is sleeping, Li Si is traveling, Wang Wu is listening to music; In the same way, the Chinese eat with chopsticks, the British eat with knives and forks, and the Indians eat with hands.

The compiler type refers to the type to the left of ‘=’ and the runtime type refers to the type to the right of ‘=’. When there is an inheritance relationship, it is possible that compile-time types differ from run-time types, that is, compile-time types are parent types and run-time types are subclass types. That is, a parent class reference points to a subclass object

Key points of polymorphism:

  1. Polymorphism is a polymorphism of methods, not of properties (polymorphism is independent of properties).

  2. There are three requirements for polymorphism to exist: inheritance, method overwriting, and parent class references to subclass objects.

  3. Polymorphism occurs when a superclass reference refers to a subclass object and is used to call a method that the subclass overrides.

Write code to prepare for polymorphism:

public class Programmer { public String name ="proName"; Public void writeCode(){system.out.println ("writing code............") ); } / / 2. Subclasses override the public void eat () {System. Out. Println (" eating with mouse..." ); } } public class Chinese extends Programmer{ public String name = "ChinName"; //1. Inherit a method writeCode() from the parent class //2. Eat public void eat() {system.out.println (" Chinese eat rice with chopsticks....." ); } public void playShadowBoxing(){system.out.println ("Chinese Play showdowBoxing every day......" ); } } public class English extends Programmer { //1. Eat public void eat() {system.out.println ("English eating meat with knife.....") ); Public void raceHorse(){system.out.println ("English like racing horse......") ); } } public class Italian extends Programmer { //1. Eat public void eat() {system.out.println ("Italian eating pizza with hand......" ); Public void playFootBall(){system.out.println ("Italian like play football....." ); }}Copy the code

Implement eat() polymorphism

public class Test { // public static void showEat(Chinese ch){ // ch.eat(); // } // public static void showEat(Italian it){ // it.eat(); // } // public static void showEat(English en){ // en.eat(); // } public static void showEat(Programmer pro){ pro.eat(); } public static void main(String[] args) { //Chinese ch = new Chinese(); Programmer ch = new Chinese(); showEat(ch); English en = new English(); showEat(en); Italian it = new Italian(); showEat(it); Programmer pro = new Programmer(); showEat(pro); } } public class Test2 { public static void main(String[] args) { Chinese ch = new Chinese(); ch.writeCode(); // ch.eat(); // Override parent ch.playshadowBoxing (); // Subclass specific method Programmer ch2 = new Chinese(); ch2.writeCode(); // non-polymorphic ch2.eat(); // ch2.playshadowBoxing (); // Cannot call subclass-specific methods}}Copy the code

Using a parent class as a method parameter is the most common case for polymorphism. Even if a new subclass is added, the method does not change and conforms to the open closed principle.

The parent class refers to the method as a parameter. The argument can be any subclass object, and different subclass objects can implement different behavior. In addition, even if a new subclass is added, the method does not need to change, which improves scalability and conforms to the open and closed principle.

The upward transition of polymorphism

Assigning a subclass object to a parent reference is called upcasting, which automatically casts the object.

Upcasting can call subclass-inherited methods, but not subclass-specific methods. In particular, it’s important to understand that if a subclass overrides a method from its parent class, then it calls the method overridden by the real subclass,

Transition up – Examples of code:

Public class TestPoly {public static void main(String[] args) {public static void main(String[] args) { System.out.println( n ); double d = n; System.out.println(d); // Automatic conversion of reference data type Programmer = new Chinese(); // Automatically convert up transition left > right programmer. WriteCode (); programmer.eat(); //programmer.playShadowBoxing(); }}Copy the code

How to understand upward transition?

  1. Programmer wanted, a British programmer, meet the requirements, no special declaration required

  2. Regardless of nationality, the written code is Java code

  3. Rest at noon, we all went to the canteen to eat, the true colors

  4. The boss looks for a programmer casually, say horse racing together, can’t; It could be a Chinese or An Italian programmer

The downward transformation of polymorphism

Casting a reference variable of a parent class to a subclass type is called downcasting. You can call subclass-specific methods once you’ve transitioned down.

  • Chinese CH = (Chinese)pro;
  • Cast is not surgery, it must be cast to a real subtype, otherwise ClassCastException;
  • There must have been an upward transition before the downward transition
  • To avoid a ClassCastException, use Instanceof before you transition down

Pro Instanceof Italian object Instanceof class or interface

The premise of instancof is that the object on the left and the type on the right have a hierarchy on the inheritance tree

Downtransition – Code examples:

Public class TestPoly2 {public static void main(String[] args) {public static void main(String[] args) {double d = 3.14; System.out.println(d); int n = (int)d; System.out.println(n); // Cast reference data type Programmer = new Chinese(); programmer.eat(); / / polymorphism / / programmer. PlayShadowBoxing (); // Chinese ch = (Chinese) programmer; Ch.playshadowboxing (); ch.playshadowBoxing (); // // English en = (English)programmer; // en.raceHorse(); if(programmer instanceof Chinese){ Chinese ch = (Chinese) programmer; ch.playShadowBoxing(); }else if(programmer instanceof English){ English en = (English) programmer; en.raceHorse(); }else{ Italian it = (Italian) programmer; it.playFootBall(); } //java.lang.ClassCastException: // com.bjsxt.poly0.Chinese cannot be cast to com.bjsxt.poly0.English System.out.println(programmer instanceof Chinese); //false System.out.println(programmer instanceof English); //true System.out.println(programmer instanceof Programmer); //true System.out.println(programmer instanceof Object); //true //System.out.println(programmer instanceof String); }}Copy the code

Note that the sum of polymorphisms is related to methods, not attributes. As shown in the following example.

Polymorphism and attribute independent – Examples of code:

public class TestPoly3 { public static void main(String[] args) { Chinese chinese = new Chinese(); System.out.println(chinese.name); Programmer programmer = new Programmer(); System.out.println(programmer.name); Programmer programmer2 = new Chinese(); System.out.println(programmer2.name); //ChinName proName programmer2.eat(); }}Copy the code

Polymorphic implementation of the simple factory pattern – the return value is the parent class type

The parent class can be used not only as a parameter to a method, but also as the return type of the method. The actual returned object can be any subclass object of that class.

Code examples:

Public class TestPoly4 {public static void main(String[] args) {public static void main(String[] args) { Programmer pro = SxtSchool.getProgrammer("en"); Pro.writecode (); } } class SxtSchool{ public static Programmer getProgrammer(String type){ Programmer pro = null; if("ch".equals(type)){ pro = new Chinese(); }else if("en".equals(type)){ pro = new English(); }else{ pro = new Italian(); } return pro; }}Copy the code

The code above is actually an implementation of the simple factory pattern, which is a solution to a large number of object creation problems. Create and use are separated, with the factory responsible for creation and the consumer calling it directly. The basic requirements of the simple factory pattern are

  1. Define a static method that is called directly by the class name
  2. The return value type is a superclass type, which can return any of its subclass types
  3. You pass in a parameter of type string, and the factory creates the corresponding subclass product based on the parameter

If you are interested, please go and have a try

The above is all the content of this chapter, I will update the follow-up oh, like the partner support oh ~

Thanks for watching ~