Question

So I've searched hoping to find some sort of idea or way of going about it.

I have a base class named movie with instance variables of id, name, loaned and borrower. This movie class is then derived by two classes bluray and dvd. Basically long story short they are all built within a library class that i'm building. Within the movie type I want to create an enum variable named genre which holds the genre's that can be applied to the movie. However I am not sure how I go about inheriting this enum variable to the bluray and dvd class.

I've been told it can be done but if anyone can shed some light on how I go about this that'd be great!

Était-ce utile?

La solution

Within the movie type I want to create an enum variable named genre which holds the genre's that can be applied to the movie. However I am not sure how I go about inheriting this enum variable to the bluray and dvd class.

Just make it a member of the movie type that isn't private. (Or just an enum in the same package, outside the movie type.) Then the bluray and dvd classes will have access to it.

Example:

Movie.java:

public class Movie {

    public enum Genre {
        Horror,
        SciFi,
        RomCom
    };

    protected Genre genre;

    public Movie(Genre g) {
        this.genre = g;
    }
}

BluRay.java:

public class BluRay extends Movie {

    public BluRay(Genre g) {
        super(g);
    }
}

Note that Genre doesn't have to be within Movie at all, and you may well be better off if it isn't (just in the same package or similar). But if you want Genre in Movie, you can have it there.


Side note: You didn't ask for feedback on your design, but FWIW I probably wouldn't make Genre an enum, because then you have to recompile in order to add genres, which seems like a common operation.

Autres conseils

You can just declare the enum separate from your class (in a new file) and then use in the movie class in which I declare a variable movie_type of the type of the enum.

When you want to use members of parent class you must provide a access to it.

Java specyfie the access modyfier as public, protected, (default), private.

If you set the access modyfier to protected you will be able to read and write to that member.

BTW

The idea to store the gender in form of enum is not the best desing as gender change and you will have to add each of them at the start of your application.

The good solution for enum would be the device type. Such as DVD or CD as this is something that you can manage in easy way.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top