多态分类
1.编译时多态(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. 其他多态特性
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 toglobal variables
within alocal 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