Reputation: 47
so Ive been trying to set values to an object within an object with no luck. This is what I need to do.
Class 1: Interface (main) With MovieDatabase object
Class 2: MovieDatabase with Movie Object
Class 3: Movie with 4 values needed. Name of movie,director etc.
I've previously only used one object and accessed that through another class but I'm not sure how to do this when it's an object within an object. Any examples using the classes above would be appreciated.
Upvotes: 0
Views: 9739
Reputation: 526
A quick example
Movie
Class
public class Movie {
private String name;
private String director;
public Movie(String name,String director){
this.name=name;
this.director=director;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
}
MovieDatabase
which contains a list of Movie objects
public class MovieDatabase {
List<Movie> movies = new ArrayList<>();
public List<Movie> getMovies() {
return movies;
}
public void setMovies(List<Movie> movies) {
this.movies = movies;
}
}
Now let's try to create some
Movie
objects and add them to the list ofMovie
objects which is a field inMovieDatabase
Class
public class stackoverflow {
public static void main(String[] args) {
// TODO code application logic here
Movie a,b,c,d;
MovieDatabase db = new MovieDatabase();
a = new Movie("Movie1","Director1");
b = new Movie("Movie2","Director2");
c = new Movie("Movie3","Director3");
d = new Movie("Movie4","Director4");
db.movies.add(a);
db.movies.add(b);
db.movies.add(c);
db.movies.add(d);
for(Movie movie : db.movies)
System.out.println("the movie "+movie.getName()+" is directed by "+movie.getDirector());
}
}
The output :
the movie Movie1 is directed by Director1
the movie Movie2 is directed by Director2
the movie Movie3 is directed by Director3
the movie Movie4 is directed by Director4
Upvotes: 4