专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java语言是如何实现多态的?(java语言中是如何实现多态的?)

temp10 2024-09-27 22:55:06 java教程 9 ℃ 0 评论

本质上多态分两种:

1.编译时多态

Java语言是如何实现多态的?(java语言中是如何实现多态的?)

(compile-time polymorphism) /(static polymorphism )

重载(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.运行时多态

(runtime polymorphism)/(dynamic polymorphism)

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

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. 其他多态特性(Other Polymorphic Characteristics)

1. 强制转换(Coercion)

String str = “string” + 2;

2. 操作符重载( Operator Overloading)

String str = "2" + 2; // 22

int sum = 2 + 2; //4

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;

}

}

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

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表