简体   繁体   中英

Implement a concrete class in Java?

Specifically, say I have an interface Movie, and concrete classes Action and Romance that implement Movies. Then, can I have a class Action-Romance that extends Action and Implements Romance? Romance is a fully implemented concrete class.

I looked up similar questions but they are not specific about whether the class that is being implemented is an interface, an abstract class, or a concrete class.

No. Java has a single-implementation-inheritance model. That means you can't inherit from two concrete superclasses. You can implement multiple interfaces, but only ever a single concrete class.

Java does not support multiple-inheritance you have to do it (for example) this way:

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

    }

}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM