Java - 20 面向对象编程的三大特征:多态

wxrwajiez / 2024-10-19 / 原文

Java - 20 面向对象编程的三大特征:多态

提高复用性

方法或对象具有多种形态,多态建立在封装和继承基础之上

方法的多态

// 重载体现多态
System.out.println(a.sum(10, 20));
System.out.println(a.sum(10, 20, 30));
// 重写体现多态
System.out.println(a.sum(10, 20));
System.out.println(b.sum(10, 20));

对象的多态(核心)

  1. 一个对象的编译类型和运行类型可以不一致

父类的引用指向子类的对象

Animal animal = new Dog(); // 编译类型是Animal,运行类型是Dog
  1. 编译类型在定义对象时就确定了,不能改变
  2. 运行类型是可以改变的
animal = new Cat();

e.g. 方法看运行类型

Animal animal = new Dog();
animal.cry(); // 执行Dog的cry()

e.g.

public void feed(Animal animal, Food food){
    System.out.println("主人" + name + "给" + animal.getName() + "喂食");
}

向上转型

Animal animal = new Cat();
  • 本质:父类的引用指向了子类的对象

  • 可以调用父类的所有成员(需遵守访问权限)

  • 不能调用子类中特有成员(因为在编译阶段,能调用哪些成员 是由 编译类型 来决定的)

属性没有重写

属性的值看编译类型

public class Main{
    public static void main(String[] args){
        Base base = new Sub();
        System.out.println(base.count); // 10 
    }
}

class Base{
    int count = 10;
}
class Sub extends Base{
    int count = 20;
}

instanceof

xx的运行类型是否为xx的子类型

Base base = new Sub();
System.out.println(base instanceof Base); // ture
System.out.println(base instanceof Sub); // true

向下转型

Cat cat = (Cat) animal; // 编译类型Cat,运行类型Cat; cat, animal指向同一个Cat对象
  • 只能强转父类的引用,不能强转父类的对象
  • 父类的引用必须指向强转类型的对象