【问题标题】:Implement a concrete class in Java?用Java实现一个具体的类?
【发布时间】:2016-08-27 20:44:36
【问题描述】:

具体来说,假设我有一个接口 Movie,以及实现 Movies 的具体类 Action 和 Romance。那么,我可以有一个类 Action-Romance 扩展 Action 并实现 Romance 吗? Romance 是一个完全实现的具体类。

我查找了类似的问题,但没有具体说明正在实现的类是接口、抽象类还是具体类。

【问题讨论】:

  • 。 Java 不支持类的多重继承(现在如果 Romance 也是 interface...)
  • 在您给出的示例中,我不会为每种电影类型创建一个子类 - 相反,我会创建一个“类型”枚举,并且每部电影都有这些类型的列表。想象一下,每次你想到一个新的流派时,你必须添加多少代码......

标签: java inheritance interface multiple-inheritance superclass


【解决方案1】:

没有。 Java 有一个单一实现继承模型。这意味着您不能从两个具体的超类继承。您可以实现多个接口,但永远只有一个具体的类。

【讨论】:

    【解决方案2】:

    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());
    
        }
    
    }`
    

    【讨论】:

      猜你喜欢
      • 2019-05-16
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      相关资源
      最近更新 更多