OOP attribute inheritance

I am facing some problems in OOP with inheritance inside a class with a specific attribute. I still haven't found a simple solution, but maybe I don't have good keywords.

OK, so let's say that I have the following classes:

public class Video{ } public class Movie extends Video{ } public class TVSerie extends Video{ } 

Both films and TVSerie must have an attribute, which is a list of participants. However, the actors may be slightly different for TVSerie and Movie, so I created the following classes of Actors:

 public class Actor{ String name; String role; } public class MovieActor extends Actor{ double compensation; } public class TVSerieActor extends Actor{ boolean guestStar; int numberOfEpisodes; } 

Basically all I want is access to the list of Actors in the video instance, but I donโ€™t know where to declare each list. Right now, Iโ€™ve added a list of specific actors for TVSerie and Movie, but that doesnโ€™t seem right, because I have to check the type of my video instance to get a list of a specific actor, while all I need is a parent actor.

Thanks for your help.

+4
source share
2 answers

This problem can be solved using generics using parameters of a limited type:

 public class Video<A extends Actor> { protected List<A> actors; public List<A> getActors() { return actors; } } public class Movie extends Video<MovieActor> {} public class TVSerie extends Video<TVSerieActor> {} 

That way, you can use a list of specific MoveActor if you know that Video is a Movie , but you can also use the same list as a simple List<Actor> if you don't know (or don't care) what type of Video has instance actually.

+3
source

Using existing classes, why not put ..

 protected List<Actor> actors; 

in your classroom video? Thus, each instance of Movie or TVSeries will have its own list of participants. Using the protected keyword, you allow two subclasses to access a variable. Then simply assign the appropriate subclass of the actor when creating or modifying the list.

 public class Video{ protected List<Actor> actors; public Video(){ actors = new ArrayList<Actor>(); } // Here you can get the actors for any instance of // Video or any of its subclasses public List<Actor> getActors(){ return actors; } } public class Movie{ public Movie(){ super(); //read movies from db etc.. actors.add(new MovieActor()); } } 
+1
source

Source: https://habr.com/ru/post/1496612/


All Articles