Home  >  Article  >  Java  >  An introduction to the concepts and implementation methods of Java inheritance and polymorphism

An introduction to the concepts and implementation methods of Java inheritance and polymorphism

WBOY
WBOYforward
2023-04-27 15:46:081347browse

    1. Inheritance

    1. The concept of inheritance

    Inheritance mechanism: Object-oriented programming is The most important means of code reuse allows programmers to extend and add new functions while maintaining the characteristics of the original class. The new class generated becomes a derived class/subclass. The main problem that inheritance solves is: extraction of common features and realization of code reuse.

    An introduction to the concepts and implementation methods of Java inheritance and polymorphism

    2. Inheritance syntax

    indicates the inheritance relationship between classes. You need to use the keyword extends. The syntax is as follows:

    Modifier class subclass/derived class extends parent class/base class/superclass{

    //…………

    }

    • The subclass will inherit the member variables or member methods of the parent class into the subclass

    • After the subclass inherits the parent class, it must add its own unique members , reflecting the difference from the base class

    3. Parent class member access

    (1) Accessing the member variables of the parent class in the subclass
    • When there is no member variable with the same name, normal access is enough.

    • If there is a member variable with the same name, use (super. variable name) to access the parent class member variable

    public class Base {
        int a;
        int b;
        int c;
    } 
    public class Derived extends Base{
        int a; // 与父类中成员a同名,且类型相同
        char b; // 与父类中成员b同名,但类型不同
        public void method(){
            a = 100; // 访问父类继承的a,还是子类自己新增的a?
            b = 101; // 访问父类继承的b,还是子类自己新增的b?
            c = 102; // 子类没有c,访问的肯定是从父类继承下来的c
        }
    }
    • When accessing member variables, access your own member variables first. That is, when accessing member variables with the same name, access to subclasses is given priority. That is: the subclass hides the members of the parent class

    • Member variable access follows the principle of proximity. If you have one, you have priority. If you don’t have it, you will look for it in the parent class.

    (2) Access the member methods of the parent class in the subclass
    • The member methods have different names and can be accessed normally

    • The member methods have the same name, and you can access the parent class method with the same name through [super.method name]

    If the parameter lists of the parent class and subclass methods with the same name are different ( Overloading), select the appropriate method to access based on the parameters passed when calling the method.

    If the prototypes of the methods with the same name of the parent class and the subclass are consistent, then access the subclass's

    4, super keyword

    The main function of the super keyword is: in the subclass Access members of the parent class with the same name in a class method. (Can only be used in non-static methods)

    public class Base {
        int a;
        int b;
        public void methodA(){
            System.out.println("Base中的methodA()");
        }
        public void methodB(){
            System.out.println("Base中的methodB()");
    }
    public class Derived extends Base{
        int a; 
        char b; 
        // 与父类中methodA()构成重载
        public void methodA(int a) {
            System.out.println("Derived中的method()方法");
        }
        // 与父类中methodB()构成重写
        public void methodB(){
            System.out.println("Derived中的methodB()方法");
        }
        public void methodC(){
            a = 100; // 等价于: this.a = 100;
            b = 101; // 等价于: this.b = 101;
            // 访问父类的成员变量时,需要借助super关键字
            // super是获取到子类对象中从基类继承下来的部分
            super.a = 200;
            super.b = 201;
            methodA(); // 没有传参,访问父类中的methodA()
            methodA(20); // 传递int参数,访问子类中的methodA(int)
            methodB(); // 直接访问,则永远访问到的都是子类中的methodA(),基类的无法访问到
            super.methodB(); // 访问基类的methodB()
        }
    }

    5. Subclass construction method

    When constructing a subclass object, you need to first call the construction method of the parent class, and then execute the construction of the subclass method.

    public class Base {
        public Base(){
            System.out.println("Base()");
        }
    }
    public class Derived extends Base{
        public Derived(){
       // super(); // 注意子类构造方法中默认会调用基类的无参构造方法:super(),
       // 用户没有写时,编译器会自动添加,而且super()必须是子类构造方法中第一条语句,
       // 并且只能出现一次
            System.out.println("Derived()");
        }
    }
    • If the parent class explicitly defines a parameterless or default constructor, there will be an implicit super() call by default in the first line of the subclass's constructor.

    • When the parent class defines a constructor with parameters, the compiler will no longer generate a default constructor for the subclass. The subclass needs to be explicitly defined and included in the subclass constructor. Call the appropriate parent class construction method

    • In the subclass construction method, super(……) calls the parent class construction method and must be the first statement of the subclass construction method

    • super(……) can only appear once in the subclass constructor, and cannot appear at the same time as this

    6. and this

    Both super and this can be used in member methods to access member variables and call other member functions. Both can be used as the first statement of the constructor. So what is the difference between them?

    (1) The same points

    • are all java keywords

    • can only be used in non-static methods of the class Used to access non-static member methods and properties

    • must be used as the first statement in the constructor, and cannot exist at the same time

    (2) The difference

    • this is a reference to the current object, and super is a reference to the members of the subclass object inherited from the parent class

    • this is a hidden parameter of non-static member methods, super is not a hidden parameter

    • In the constructor: this() is used to call the constructor of this class, super() is used to call the parent Class construction method, the two calls cannot appear in the construction method at the same time

    • There will definitely be a call to super() in the construction method of the subclass, but this() will not exist if the user does not write it

    7. Code block execution order

    [Common class]

    • Static code blocks are executed first and only once , executed during the class loading phase

    • When an object is created, the instance code block will be executed, and finally the constructor method

    [Inheritance relationship Execution order]

    • The parent class static code block takes precedence over the child class static code block, and the earliest execution

    • The parent class instance code block And the parent class constructor method is executed immediately

    • The instance code block of the subclass and the constructor method are finally executed

    • The second instantiation of the subclass object, the static code blocks of the parent class and subclass will no longer be executed

    8、继承方式

    【注】Java中不支持多继承

    An introduction to the concepts and implementation methods of Java inheritance and polymorphism

    • super只能指代直接父类

    • 继承关系一般不超过三层

    9、final关键字

    • 修饰变量时,表示常量(不能修改)

    • 修饰类:此类不能被继承

    • 修饰方法:表示方法不能被重写

    10、继承和组合

    组合和继承都能实现代码的复用。组合没有涉及到特殊的语法(如extend关键字),仅仅是将一个类的实例作为另一个类的属性。

    • 继承表示对象与对象之间是is-a的关系

    • 组合表示对象与对象之间是has-a的关系

    一般建议:能用组合尽量用组合

    二、多态

    1、向上转型

    通过父类类型的引用调用子类对象,向上转型是安全的

    【发生向上转型的时机】

    • 直接赋值

    • 方法传参

    • 函数的返回值

    public class TestAnimal {
        // 2. 函数传参:形参为父类引用,可以接收任意子类的对象
        public static void eatFood(Animal a) {
            a.eat();
        }
     
        // 3. 作返回值:返回任意子类对象
        public static Animal buyAnimal(String var) {
            if ("狗" == var) {
                return new Dog("狗狗", 1);
            } else if ("猫" == var) {
                return new Cat("猫猫", 1);
            } else {
                return null;
            }
        }
     
        public static void main(String[] args) {
            Animal cat = new Cat("元宝", 2); // 1. 直接赋值:子类对象赋值给父类对象
            Dog dog = new Dog("小七", 1);
        }
    }

    优缺点:

    • 优点:让代码更加灵活

    • 缺点:不能访问到子类特有的方法

    2、重写

    函数名相同、参数列表相同、返回值相同或是【协变类型】(父子类关系)

    【方法重写的规则】

    • 重写的方法访问权限不能比父类中原方法的的权限低;

    • 父类中被static、private、final修饰的方法、构造方法不能被重写;

    • 重写的方法,可以使用 @override 注解来显示指定(帮助我们进行一些合法性的检验)。比如方法名拼写错误,编译会报错;

    • 重写的返回值类型可以不同,但是必须具有父子关系。

    • 被final修饰的方法,叫做密封方法,该方法不能被重写。

    • 外部类只能是public或者默认权限

    【动态绑定和静态绑定】

    • 动态绑定:发生的条件(1、父类引用引用子类对象;2、通过父类引用,可以访问到子类中的方法)。后期绑定,即在编译时不能确定方法的行为,需要等到程序运行时,才能够确定调用哪个类的方法;

    • 静态绑定:前期绑定,编译时,根据用户传递的参数类型确定具体的调用方法(函数重载)

    3、多态

    一个引用调用同一个方法,可以表现出不同的形式,这种思想称为多态。在父类的构造方法中不要调用重写的方法。

    【多态实现的条件】

    • 必须在继承条件下

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

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

    • 发生了向上转型

    public class Animal(){
        String name;
        int age;
        public Animal(String name, int age){
            this.name = name;
            this.age = age;
        }
        public void eat(){
            System.out.println(name + "吃饭");
            }
    }
    public class Cat extends Animal{
        public Cat(String name, int age){
            super(name, age);
        }
        @Override
        public void eat(){
            System.out.println(name+"吃鱼~~~");
        }
    }
    public class Dog extends Animal {
        public Dog(String name, int age){
            super(name, age);
        }
        @Override
        public void eat(){
            System.out.println(name+"吃骨头~~~");
        }
    }
    public class TestAnimal {
        // 编译器在编译代码时,并不知道要调用Dog 还是 Cat 中eat的方法
       // 等程序运行起来后,形参a引用的具体对象确定后,才知道调用那个方法
       // 注意:此处的形参类型必须时父类类型才可以
        public static void eat(Animal a){
            a.eat();
        }
        public static void main(String[] args) {
            Animal animal1 = new Cat("元宝",2);
            Animal animal2 = new Dog("小七", 1);
            eat(animal1);
            eat(animal2);
        }
    }

    【注】Java中所有的类默认继承Object类

    The above is the detailed content of An introduction to the concepts and implementation methods of Java inheritance and polymorphism. 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