Java语言是如何实现多态的?

多态分类

本质上多态分多种,主要有两种
1.编译时多态(compile-time polymorphism) /(static polymorphism )
2.运行时多态(runtime polymorphism)/(dynamic polymorphism)


1.编译时多态

1.1 方法重载(overload)

public class TextFileStaticPolymorphism {

	public String read() {
		return "StaticPolymorphism".toString();
	}

	public String read(int limit) {
		return "StaticPolymorphism".substring(0, limit);
	}

	public String read(int start, int stop) {
		return "StaticPolymorphism".substring(start, stop);
	}
}

2.运行时多态

我们通常所说的多态指的都是运行时多态,也就是编译时不确定究竟调用哪个具体方法,一直到运行时才能确定。

Java实现多态有 3 个必要条件:

继承重写向上转型。 只有满足这 3 个条件,开发人员才能够在同一个继承结构中使用统一的逻辑实现代码处理不同的对象,从而执行不同的行为

public class GenericFile {
    public String getFileInfo() {
        return "Generic File Impl";
    }
}

public class ImageFile extends GenericFile {
    public String getFileInfo() {
        return "Image File Impl";
    }
}

GenericFile genericFile = new GenericFile();
String message = genericFile.getFileInfo();
System.out.println(message);

GenericFile genericFile2 = new ImageFile();
message = genericFile2.getFileInfo();
System.out.println(message);

输出结果
Generic File Impl
Image File Impl

3. 其他多态特性

3.1. 强制转换(Coercion)

String str = "string" + 2;

3.2. 操作符重载( Operator Overloading)

String str = "2" + 2; // 22
int sum = 2 + 2; //4

3.3. 多态参数(Polymorphic Parameters)

use this keyword to point to global variables within a local context.

public class TextFile extends GenericFile {
    private String content;
    
    public String setContentDelimiter() {
        int content = 100;
        this.content = this.content + content;
    }
}

3.4.多态子类型(Polymorphic Subtypes)

Polymorphic subtype conveniently makes it possible for us to assign multiple subtypes to a type and expect all invocations on the type to trigger the available definitions in the subtype.
多态子类型使我们可以方便地将多个子类型分配给一个类型,并期望对该类型的调用都能触发子类型中的可用定义

GenericFile[] files = {new ImageFile(), new TextFile()};

for (int i = 0; i < files.length; i++) {
    System.out.println(files[i].getFileInfo());
}

// 输出结果
Image File Impl
Text File Impl

参考

Polymorphism in Java

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值