Wie kann ich ein Objekt mit einem anderen Objekt in Java verknüpfen?

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Wie kann ich ein Objekt mit einem anderen Objekt in Java verknüpfen?

by Guest » 04 Jan 2025, 06:17

Ich erstelle eine Kinoanwendung in Java und benötige Hilfe beim Verknüpfen von Objekten. Ich habe drei Klassen erstellt: Person, Film und Extra.
Derzeit habe ich ein Szenario, in dem eine Person (wie John oder Sam) einen Film (wie „Fight Club“) hinzufügen kann. zu ihrer Filmliste. Ich möchte sicherstellen, dass jede Person unterschiedliche Extras für denselben Film auswählen kann. Wenn ich jedoch einem Film ein Extra (z. B. „Popcorn“) hinzufüge, wird es für alle Personen hinzugefügt, die diesen Film ansehen, und nicht nur für die einzelne Person.
Hier ist ein Beispiel:
John möchte „Fight Club“ sehen und das Extra „Popcorn“ hinzufügen.
Sam möchte den gleichen Film sehen, bevorzugt aber das Extra „Drink“.
Das Problem ist, dass, wenn ich „Popcorn“ hinzufüge Film, wird es letztendlich sowohl für John als auch für Sam zum Film hinzugefügt, anstatt nur für John.
Hier ist mein Code:
Person:

Code: Select all

public class Person {
private String name;
private int attendeesCount;
private List movies;

public Person(String name, int attendeesCount) {
this.name = name;
this.attendeesCount = attendeesCount;
this.movies = new ArrayList();
}

public void addMovie(Movie movie) {
movies.add(movie);
}
}
Film:

Code: Select all

public class Movie {
private String title, description;
private int price, duration;
private List extras = new ArrayList();

private Movie(String title, int price, String description, int duration) {
this.title = title;
this.price = price;
this.description = description;
this.duration = duration;
}

public void addExtra(Extra extra) {
this.extras.add(extra);
}
}
Extra:

Code: Select all

public class Extra {
private String name;
private int price;

public Extra(String name, int price) {
this.name = name;
this.price= price;
}
}
Hauptseite:

Code: Select all

public class TestTheatre {
public static void main(String[] args) {
Movie fightClub = new Movie("Fight Club", 1000, null, 90);
Movie theMatrix = new Movie("The Matrix", 2000, null, 80);

Extra popcorn = new Extra("Popcorn", 500);
Extra drink = new Extra("Drink", 400);

fightClub.addExtra(popcorn); // Here is where I am adding the extra to the movie

Person john = new Person("John", 2);
Person sam = new Person("Sam", 3);

john.addMovie(fightClub);
john.addMovie(theMatrix);

sam.addMovie(fightClub);
}
}
Ich verstehe, dass das Problem auftritt, weil ich dem Film global Extras hinzufüge, wodurch die Extras auf alle Personen angewendet werden, die sich diesen Film ansehen. Ich weiß jedoch einfach nicht, wie ich das machen soll kann das lösen. Jede Hilfe wäre sehr dankbar.

Top