前言
面向对象的三大特性:封装、继承、多态。从一定角度来看,封装和继承几乎都是为多态而准备的。那什么是多态,就来了解一下。
定义
指允许不同类的对象对同一消息做出响应。即同一消息可以根据发送对象的不同而采用多种不同的行为方式。(发送消息就是函数调用)。
多态是同一个行为具有多个不同表现形式或形态的能力。
多态就是同一个接口,使用不同的实例而执行不同操作
多态优点:
- 消除类型之间的耦合关系
- 可替换性
- 可扩充性
- 接口性
- 灵活性
- 简化性
多态存在的三个必要条件:
1、要有继承;
2、要有重写;
3、父类引用指向子类对象。
多态的实现方式
方式一:重写与重载
Java 重写(Override)与重载(Overload)。
方式二:抽象类和抽象方法
使用abstract修饰的类称之为抽象类
使用abstract修饰且没有方法体的方法称之为抽象方法
注意
具有抽象方法的类一定是抽象类但抽象类不一定有抽象方法。
子类继承父类,要么子类必须重写父类中的抽象方法,要么子类也是抽象类。
public abstract class Animal {
public abstract void eat();
public void drink() {
}
class Dog extends Animal{
@Override
public void eat() {
}
}
}
方式三:接口
简介:接口就是给出一些还没有实现的方法,封装到一起,到某个类要使用的时候,在根据具体情况把这些方法写出来。
定义两个接口:
public interface Interface01 {
void fun01();
}
public interface Interface02 {
void fun02();
}
定义第三个接口并继承01,02:
public interface Interface03 extends Interface01,Interface02 {
void fun03();
}
实现接口:
public class Interface03Impl implements Interface03 {
@Override
public void fun01() {
System.out.println("fun01");
}
@Override
public void fun02() {
System.out.println("fun02");
}
@Override
public void fun03() {
System.out.println("fun03");
}
}
实现接口的测试类:
public class Interface03Test {
@Test
public void test(){
Interface03 interface03 = new Interface03Impl();
interface03.fun01();
interface03.fun02();
interface03.fun03();
}
}
运行结果:
注意:
- 在接口中的方法为抽象方法,不允许出现方法体
- 从java8开始允许接口中的方法有方法体,但必须使用default或static修饰
- 在接口中 static 修饰的方法:
只能使用接口名点方法名的方式调用不能使用实现类的实例化对象调用 (与静态方法点用类似)
不可以被子接口继承- 在接口中 default 修饰的方法
只能使用实现类的实例化对象调用
可以被子接口继承
可以被子接口重写
可以被实现类重写- 接口中的成员变量为静态常量,只能通过接口名点方法名的方式调用
函数式接口
- 当接口中只有一个抽象方法的时候我们称这个接口为函数式接口。
- 可以使用FunctionalInterface注解修饰但不是必须的。
- 使用FunctionalInterface注解修饰的函数式接口会增加校验。
定义一个函数式接口:
@FunctionalInterface
public interface Interface04 {
void eat();
}
直接测试类实现接口(以下是测试类接口实现的普通形式和lambda表达式形式):
public class Interface04Test {
@Test
public void test() {
new Interface04() {
@Override
public void eat() {
System.out.println("苹果");
}
}.eat();
}
@Test
public void test01() {
Interface04 interface04 = new Interface04() {
@Override
public void eat() {
System.out.println("苹果");
}
};
interface04.eat();
}
@Test
public void test02() {
Interface04 interface04 = () -> System.out.println("苹果");
interface04.eat();
}
}
java中还提供了诸多预置的函数接口,请点击查看。