This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging

⭐ August more text challenge day 12 ⭐, review and consolidate Java😁 with friends

Code Mantis shrimp is a sand sculpture and interesting young boy, like most friends like listening to music, games, of course, in addition to the interest of writing, Emm… There is still a long time to go. Let’s work hard together 🌈

Welcome friends to pay attention to my public number: JavaCodes, although the name with Java, but the scope of more than Java field oh 😁, look forward to your attention ❤

Self-recommendation, to recommend their own column 😁, welcome friends to collect attention 😊

MybatisPlus column

App Crawler Column

PC crawler column

Big factory interview questions column


Java update directory details at 😁

🌈Java from entry to grave ⭐ study notes ⭐ (1) String Common methods summary 😊 (small white essential knowledge!!

🌈Java from entry to grave ⭐ study notes ⭐ (2) final, static keywords summary 😊 (small white necessary knowledge points!!

🌈Java from entry to grave ⭐ study notes ⭐ (3) encapsulation and four kinds of permission modifiers detailed explanation 😊 (small white essential knowledge!

🌈Java from entry to grave ⭐ Study notes ⭐ (4) small white essential object-oriented – the definition and use of inheritance

🌈Java from entry to grave ✨ Study notes ✨ (5) Small white essential object-oriented – detailed explanation of polymorphism


1. Overview of polymorphism

What is polymorphism?

The polymorphism of an object in which a parent reference points to an object in a subclass (or a reference that a subclass object assigns to a parent)

Use of polymorphisms

With object polymorphism, we can only call methods declared by the parent class at compile time, but at run time, we are actually executing methods that the child class overwrites.

Summary: Compile on the left, run on the right

Three necessary conditions for the existence of polymorphisms

  1. inheritance
  2. rewrite
  3. A parent class reference points to a child class object

2. Use of polymorphisms

Polymorphism definition format: superclass variable name = new subclass ();

public class Main {

    public void fun(Person person) {
        person.study();
        person.sleep();
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.fun(new Student());

        System.out.println("-- -- -- -- -- -- -- -- --");
        main.fun(newTeacher()); }}class Person{

    public void study(a){
        System.out.println("Learning");
    }

    public void sleep(a){
        System.out.println("Sleep"); }}class Student extends Person{

    public void study(a){
        System.out.println(Student Learning);
    }

    public void sleep(a){
        System.out.println(Student sleeping); }}class Teacher extends Person{
    public void study(a){
        System.out.println("Teacher learning");
    }

    public void sleep(a){
        System.out.println("Teacher sleeping"); }}Copy the code


3, polymorphism is not applicable

We define the ID value in Person, Studen, and Teacher

public class Main {

    public void fun(Person person) {
        person.study();
        person.sleep();
    }

    public static void main(String[] args) {
        Person student = new Student();
        System.out.println(student.id);

        Person teacher = newTeacher(); System.out.println(teacher.id); }}class Person{
    int id = 200;
}

class Student extends Person{
    int id = 50;
}


class Teacher extends Person{
    int id = 100;
}
Copy the code

== Conclusion == : Polymorphism applies only to methods, not to attributes (== compile and run both see left ==)


Use of the instanceof keyword

A instanceof a: determines whether object a is an instanceof class a. If so, return true; If not, return false.

public static void main(String[] args) {
        Person student = new Student();

        Person teacher = new Teacher();

        System.out.println(student instanceof Person);
        System.out.println(teacher instanceof Person);

        System.out.println(student instanceof Teacher);
    }
Copy the code

Use strong turn

System.out.println((Teacher)student instanceof Teacher);
Copy the code

Conclusion: In order to avoid the occurrence of ==ClassCastException== during the downward transition, we first judge ==instance== before the downward transition, and as soon as ==true== is returned, the downward transition is performed. If return ==false==, no downward transformation is performed.

** This is also true if ==instanceof== multiple inheritance

For example, a inherits from a, and a inherits from B, so ==a instanceof a returns true, and a instanceof B returns true==**


5. Polymorphic transformation

== Upward transition ==

  • When a subclass object is assigned to a reference to a parent class, it is transitioned upward (polymorphism itself is the process of transitioning upward)
  • Format: superclass type variable name = new subclass type ();

== Downward transformation ==

  • The parent class reference is converted to the subclass format by casting the format
  • Format: subclass type variable name = (subclass type) subclass type variable name;
public class Main {


    public static void main(String[] args) {
        Person person = new Student();

        Student student = new Student(); // Upward transition
        Student student1 = (Student)person; // Downward transitionstudent.sleep(); student1.sleep(); }}class Person{
    public void sleep(a) {
        System.out.println("Sleep"); }}class Student extends Person{
    public void sleep(a) {
        System.out.println(Student sleeping); }}Copy the code

== Precautions for downward transformation (Attention) ==

  • The downward transition assumes that the parent object refers to the subclass object (that is, it has to transition up before it can transition down).
* <font size="4"> 支那Copy the code

6. Advantages and disadvantages of polymorphism

Advantages:

  1. Improved code maintainability (guaranteed by inheritance)
  2. Improved code reusability (guaranteed by inheritance)
  3. Improved code extensibility: New subclasses do not affect the polymorphism, inheritance, and other features of existing classes
  4. Security: The upward transition hides the subclass types

Disadvantages:

  1. Can’t use subclass-specific functionality (use downcast casts if you do)





The last

I am aCode pipi shrimpI am a mantis shrimp lover who loves to share knowledge. I will keep updating my blog in the future. I look forward to your attention!!

Creation is not easy, if this blog is helpful to you, I hope you can == a key three! ==, thanks for your support, see you next time ~~~