在 Java 中实施具体的 class?
Implement a concrete class in Java?
具体来说,假设我有一个 Movie 接口,以及实现 Movies 的具体 classes Action 和 Romance。那我可不可以有一个class延伸动作实现浪漫的动作浪漫?浪漫是一个完全实现的具体 class.
我查了类似的问题,但他们没有具体说明正在实现的class是一个接口,一个抽象的class,还是一个具体的class。
没有。 Java 具有单一实现继承模型。这意味着您不能继承两个具体的超级classes。您可以实现多个接口,但只能 ever 一个具体的 class.
Java 不支持多重继承你必须这样做(例如)这样:
import java.util.ArrayList;
import java.util.List;
class Movie{
private String name;
private List<Genre> genres;
public Movie(String name){
this.name=name;
this.genres = new ArrayList<Genre>();
}
public Movie withGenre(Genre genre){
this.genres.add(genre);
return this;
}
public String getName(){
return this.name;
}
public List<Genre> getGenres(){
return this.genres;
}
}
class Genre{
private String name;
public Genre(String name){
this.name = name;
}
}
class Romance extends Genre{
public Romance() {
super("Romance");
}
}
class Comedy extends Genre{
public Comedy() {
super("Comedy");
}
}
class Main{
public static void main(String[] args) {
Movie movie1 = new Movie("A Movie").withGenre(new Romance());
Movie movie2 = new Movie("A second Movie").withGenre(new Comedy()).withGenre(new Romance());
}
}`
具体来说,假设我有一个 Movie 接口,以及实现 Movies 的具体 classes Action 和 Romance。那我可不可以有一个class延伸动作实现浪漫的动作浪漫?浪漫是一个完全实现的具体 class.
我查了类似的问题,但他们没有具体说明正在实现的class是一个接口,一个抽象的class,还是一个具体的class。
没有。 Java 具有单一实现继承模型。这意味着您不能继承两个具体的超级classes。您可以实现多个接口,但只能 ever 一个具体的 class.
Java 不支持多重继承你必须这样做(例如)这样:
import java.util.ArrayList;
import java.util.List;
class Movie{
private String name;
private List<Genre> genres;
public Movie(String name){
this.name=name;
this.genres = new ArrayList<Genre>();
}
public Movie withGenre(Genre genre){
this.genres.add(genre);
return this;
}
public String getName(){
return this.name;
}
public List<Genre> getGenres(){
return this.genres;
}
}
class Genre{
private String name;
public Genre(String name){
this.name = name;
}
}
class Romance extends Genre{
public Romance() {
super("Romance");
}
}
class Comedy extends Genre{
public Comedy() {
super("Comedy");
}
}
class Main{
public static void main(String[] args) {
Movie movie1 = new Movie("A Movie").withGenre(new Romance());
Movie movie2 = new Movie("A second Movie").withGenre(new Comedy()).withGenre(new Romance());
}
}`