Java运行时多态
通常,多态性——某事物(一个对象或另一个entity)具有多种形式
Java提供两种多态类型:静态(编译时)多态,动态(运行时)多态(static (compile-time) and dynamic (run-time) polymorphism);第一种是通过方法的重载(overloading),第二种是通过继承(inheritance)和方法重写(overriding)
细分为:
特殊多态性:是指可以应用于不同类型的参数的多态函数,但根据应用这些函数的参数的类型,它们的行为会有所不同。Java支持它作为方法重载。
子类型多态性(也称为子类型化):是在允许基类的实例时使用子类实例的一种可能性。(使用最为广泛)
参数多态性:是在编写代码时没有提及任何特定类型,因此可以透明地与任何数量的新类型一起使用。Java支持它作为泛型或泛型编程。
即使getInfo()是基类Publication的方法,它也可以调用其基类的方法getType()getDetails()。 确切地将调用getType()和getDetails的哪个“版本”是在运行时确定的,具体取决于对象的具体类型。
这段代码很好的解释了子类型多态性,在3个继承子类中重写了基类(父类)中的getType()和getDetails()
class Publication {
private String title;
public Publication(String title) {
this.title = title;
}
public final String getInfo() {
return getType() + getDetails() + title;
}
public String getType() {
return "Publication: ";
}
public String getDetails() {
return "";
}
}
class Newspaper extends Publication {
private String source;
public Newspaper(String title, String source) {
super(title);
this.source = source;
}
public String getType() {
return "Newspaper";
}
public String getDetails() {
return " (source - " + source + "): ";
}
}
class Article extends Publication {
private String author;
public Article(String title, String author) {
super(title);
this.author = author;
}
public String getType() {
return "Article";
}
public String getDetails() {
return " (author - " + author + "): ";
}
}
class Announcement extends Publication {
private int daysToExpire;
public Announcement(String title, int daysToExpire) {
super(title);
this.daysToExpire = daysToExpire;
}
public String getType() {
return "Announcement";
}
public String getDetails() {
return " (days to expire - " + daysToExpire + "): ";
}
}