Home  >  Article  >  Java  >  Java object-oriented polymorphic instance analysis

Java object-oriented polymorphic instance analysis

PHPz
PHPzforward
2023-04-19 13:34:03837browse

    Understanding of polymorphism

    What is polymorphism? ? Literally understood, it means multiple forms, that is, objects instantiated from different classes call the same method. It can also be understood that objects of different classes produce different states after the same behavior. This is polymorphism.

    To understand polymorphism, we must understand the two key points of upward transformation and rewriting, and then come to deeply understand the concept of polymorphism. After reading upward transformation and rewriting, we can look at the concept of polymorphism. , you will suddenly become enlightened and gain a lot of clarity at once. Because the conditions for polymorphism are upward transformation, rewriting and inheritance.

    Upward Transformation

    First of all, the premise of polymorphism is inheritance. Since it is inheritance, there must be a relationship between parent class and subclass.

    Let’s recall how to create subclass objects and parent class objects.

    class Animal{
        public String name;//名字
        public int age;
        public void eat() {
            System.out.println("我要吃饭!!!");
        }
        public void sleep() {
            System.out.println("我要睡觉!!!");
        }
    }
    class Cat extends Animal{
        public void mew() {
            System.out.println("喵喵喵!!!");
        }
    }
    public class TestDemo1 {
        public static void main(String[] args) {
             Cat cat =new Cat();//实例化子类对象
             cat.name="mimi";
             Animal animal = new Animal();//实例化父类对象
             animal.eat();
        }
    }

    The cat class is created here and then inherits the Animal class. We can call methods and properties by instantiating the Cat and Animal objects.

    So what is upward transformation? ? ?

    Originally, the reference of the subclass object refers to the object of the subclass, and now the reference of the parent class refers to the subclass object. This is upward transformation.

    Java object-oriented polymorphic instance analysis

    Let’s use the code to understand:

    Java object-oriented polymorphic instance analysis

    This is upward transformation, we can also use the parent class reference of animal Call method;

    Java object-oriented polymorphic instance analysis

    # At this time we will find that we can use this reference to call the methods and properties of the parent class, but we cannot call the methods and properties of the subclass, so why? ? ? The reason is that the parent class does not have this method in the subclass, so it cannot be called. Summary: During upward transformation, the parent class reference refers to the subclass object. This parent class reference can only call the attributes and methods of the parent class, but not the subclass.

    Three forms of upward transformation

    The first one: direct assignment

    That is the way we wrote it above:

      Animal animal1 = new Cat();//父类对象的引用 引用子类对象--->向上转型
      Animal animal2 = new Dog();

    The second one: As method parameters:

    Java object-oriented polymorphic instance analysis

    The third type is as return value:

    Java object-oriented polymorphic instance analysis

    Let’s go back to the printed result just now. ;

    Java object-oriented polymorphic instance analysis

    #But what if I change the method of the parent class to say I want to eat cat food? The result is no surprise that mimi wants to eat cat food.

    But this will cause a problem. If I create a dog class and then call the eat method, do dogs also need to eat cat food? This will cause problems, then we can write an eat method in the subclass;

    class Animal{
        public String name;//名字
        public int age;
        public void eat() {
            System.out.println(this.name+"要吃饭!!!");
        }
    }
    class Dog extends Animal{
        public void dark() {
            System.out.println("汪汪汪!!!");
        }
        public void eat() {
            System.out.println(this.name+"吃狗粮!!!");
        }
    }
    class Cat extends Animal{
        public void mew() {
            System.out.println("喵喵喵!!!");
        }
        public void eat() {
            System.out.println(this.name+"吃猫粮!!!");
        }
    }
    public class TestDemo1 {
        public static void main(String[] args) {
            //语法形式 : 父类 变量 = new 子类();
            Animal animal1 = new Cat();//父类对象的引用 引用子类对象--->向上转型
            Animal animal2 = new Dog();//父类对象的引用 引用子类对象--->向上转型
            animal1.name = "小猫";//访问父类属性
            animal2.name = "小狗";//访问父类属性
            animal1.eat();
            animal2.eat();
            // animal.mew();//访问子类特有的方法
        }
    }

    At this time, a dog class is created, and then two eat methods are created in the two subclasses.

    Java object-oriented polymorphic instance analysis

    # We found that it became very clear at this time to achieve the effect we wanted.

    But we should think about it again, why call the eat method of the subclass instead of the parent class?

    Dynamic binding and static binding

    Dynamic binding actually occurs at this time. We can look at the bytecode file and open the powershell window

    Java object-oriented polymorphic instance analysis

    We all know that to execute a program, you need to compile it first and then run it. This is when the animal's eat method is called when compiling, and when it is run, the cat method is called. This is what we call Runtime binding or we can say dynamic binding.

    Then since there is dynamic binding, there must be static binding as well.

    Dynamic binding is to call a method at compile time, and at runtime it is the final method to be called, that is, to determine which method to call at runtime.

    Static binding means which method to call has been determined during compilation.

    Among them, the most obvious representative of dynamic binding is method rewriting.

    The most obvious representative of static binding is method overloading.

    Let’s look back at the above method ε=(´ο`*)))...why the return value, parameter list, and method name of the previous eat method are all the same Woolen cloth? Let's take a look.

    Java object-oriented polymorphic instance analysis

    Rewriting of methods

    We have learned about method overloading before. Let’s review method overloading. Method overloading means that the method names are the same and the return values ​​are different. To make a request, the parameter list is different. The method rewriting we learned today means that the return value is the same, the method name is the same, and the parameter list is the same. It is called method rewriting, but it can also be called method overwriting.

    There are several requirements for method rewriting:

    Method rewriting must have the same method name, the same method parameter list, and the same method return value.

    Java object-oriented polymorphic instance analysis

    We can also generate rewrites with one click

    Java object-oriented polymorphic instance analysis

     有几个注意事项:

    Java object-oriented polymorphic instance analysis

     不能重写被private修饰的方法。

    Java object-oriented polymorphic instance analysis

     不能重写被final修饰的方法。

    Java object-oriented polymorphic instance analysis

     子类的方法的访问权限一定要大于等于父类的访问权限。

    Java object-oriented polymorphic instance analysis

    重写的方法, 可以使用 @Override 注解来显式指定. 有了这个注解能帮我们进行一些合法性校验. 例如不小心将方法名字拼写错了 (比如写成eat), 那么此时编译器就会发现父类中没有 aet 方法, 就会编译报错, 提示无法构成重写.

    Java object-oriented polymorphic instance analysis

    被static修饰的方法也不能被重写 

    总结方法重写的注意事项:

    • 被private,final修饰的方法不能被重写。

    • 被staitc修饰的方法也不能被重写。

    • @override 可以检查你重写的方法名是否正确,最好要加上。

    • 方法重写一定满足方法名相同,参数列表相同,返回值相同。

    对比方法重写与方法重载:

    Java object-oriented polymorphic instance analysis

    最后:重写不是进行在原来基础的修改,而是在原来基础上进行迭代和更新。

    进一步认识和理解多态

    场景:画一个图形

    class Shape{//创建一个图形类---->作为多种图形的父类
        public int length;//图形的长
        public int wide;//图形的宽
        public int height;//图形的高
        public void draw() {
            System.out.println("我要画一个图形!!!");
        }
    }
    class rectangle extends Shape{//长方形
        @Override
        public void draw() {
            System.out.println("我要画一个长方形!!!");
        }
    }
    class square extends Shape{
        @Override
        public void draw() {
            System.out.println("我要画一个正方形!!!");
        }
    }
    class circular extends Shape{
        @Override
        public void draw() {
            System.out.println("我要画一个圆形!!!");
        }
    }
    public class TestDemo1 {
        public static void method(Shape shape) {
            shape.draw();
        }
        public static void main(String[] args) {
            Shape shape1 = new circular();
            Shape shape2 = new rectangle();
            Shape shape3 = new square();
            method(shape1);
            method(shape2);
            method(shape3);
        }
    }

    创建一个Shape(父类),然后创建三个子类分别是square ,circular,rectangle,利用父类引用这三个子类,接着调用method方法。

    Java object-oriented polymorphic instance analysis

    这就是多态,不同的对象,调用同一个方法最后结果产生出不同的状态。

    我们再来总结多态产生的条件:

    • 要在继承体系下

    • 子类要对父类的方法进行重写

    • 通过父类的引用调用重写的方法 

    也就是 在继承体系下  进行向上转型  和 方法重写

    多态的优点

    优点:

    • 能够降低代码的 "圈复杂度", 避免使用大量的 if - else

    • 如果使用多态, 则不必写这么多的 if - else 分支语句, 代码更简单.

    • 可扩展能力更强

    缺点:

    • 代码的运行效率降低

    还有一个重要点就是不要在构造方法中调用重写方法

    The above is the detailed content of Java object-oriented polymorphic instance analysis. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete