у меня есть задание 1.создать, связать 3 метода и добавить наследование. 2. добавить поля всех типов. 3. добавить Методы equals & hashCode. Проверь мой код на соответствие import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RadioStationDemo {
public static void main(String[] args) {
Genre genreVideo = new Genre("MACAN - TSM", "Rap", 3, 5, (short) 40);
Bid bid = new Bid("FRIENDLY THUG 52 NGG - AMMO", "Underground rap", "Street racing", 32, (short) 35);
@Override
public int hashCode() {
return Objects.hash(name, genre, time, viewCount, rating);
}
}import java.util.Objects;
class Bid {
private String name;
private String genre;
private String bidName;
private long viewCount;
private short rating;
code
public Bid(String name, String genre, String bidName, long viewCount, short rating) {
this.name = name;
this.genre = genre;
this.bidName = bidName;
this.viewCount = viewCount;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getBidName() {
return bidName;
}
public void setBidName(String bidName) {
this.bidName = bidName;
}
public long getViewCount() {
return viewCount;
}
public void setViewCount(long viewCount) {
this.viewCount = viewCount;
}
public short getRating() {
return rating;
}
public void setRating(short rating) {
this.rating = rating;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Bid)) return false;
Bid bid = (Bid) o;
return viewCount == bid.viewCount &&
rating == bid.rating &&
Objects.equals(name, bid.name) &&
Objects.equals(genre, bid.genre) &&
Objects.equals(bidName, bid.bidName);
}
@Override
public int hashCode() {
return Objects.hash(name, genre, bidName, viewCount, rating);
}
}
Ваш код в целом выглядит хорошо, но есть некоторые улучшения, которые можно внести:
Использование наследования: Вы просите использовать наследование, но у вас этого не реализовано. Например, классы Genre и Bid могут наследовать от класса Video, так как у них есть общие поля. Это позволит уменьшить дублирование кода.
Наследование и организация кода: В вашей реализации есть три класса — Genre, Bid, и Video, которые имеют аналогичные поля. Вы можете использовать наследование, чтобы избежать дублирования.
Объедините объявления импорта: У вас объявления импорта Objects и ArrayList повторяются многократно. Поместите все импорты в начало файла.
Инкапсуляция: В вашем коде нет явных ошибок в плане инкапсуляции, однако использование наследования может упростить код и улучшить его читабельность.
Вот как может выглядеть ваш обновлённый код с использованием наследования:
java
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RadioStationDemo {
public static void main(String[] args) {
Genre genreVideo = new Genre("MACAN - TSM", "Rap", 3, 5, (short) 40);
Bid bid = new Bid("FRIENDLY THUG 52 NGG - AMMO", "Underground rap", "Street racing", 32, (short) 35);
RadioStation radioStation = new RadioStation();
radioStation.addGenre(genreVideo);
radioStation.addBid(bid);
System.out.println("Genre Information:");
System.out.println("Video Name: " + genreVideo.getName());
System.out.println("Genre: " + genreVideo.getGenre());
System.out.println("Time: " + genreVideo.getTime() + " min");
System.out.println("View Count: " + genreVideo.getViewCount());
System.out.println("Rating: " + genreVideo.getRating());
System.out.println("Bid Information:");
System.out.println("Bid Name: " + bid.getBidName());
System.out.println("Bid Video Name: " + bid.getName());
System.out.println("Bid Genre: " + bid.getGenre());
System.out.println("Bid View Count: " + bid.getViewCount());
System.out.println("Bid Rating: " + bid.getRating());
genreVideo.setTime(2);
bid.setBidName("Overnight in St. Petersburg");
System.out.println("Updated Genre Time: " + genreVideo.getTime() + " min");
System.out.println("Updated Bid Name: " + bid.getBidName());
}
}
class Video {
private String name;
private String genre;
private long viewCount;
private short rating;
public Video(String name, String genre, long viewCount, short rating) {
this.name = name;
this.genre = genre;
this.viewCount = viewCount;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public long getViewCount() {
return viewCount;
}
public void setViewCount(long viewCount) {
this.viewCount = viewCount;
}
public short getRating() {
return rating;
}
public void setRating(short rating) {
this.rating = rating;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Video)) return false;
Video video = (Video) o;
return viewCount == video.viewCount &&
rating == video.rating &&
Objects.equals(name, video.name) &&
Objects.equals(genre, video.genre);
}
@Override
public int hashCode() {
return Objects.hash(name, genre, viewCount, rating);
}
}
class Genre extends Video {
private int time;
public Genre(String name, String genre, int time, long viewCount, short rating) {
super(name, genre, viewCount, rating);
this.time = time;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Genre)) return false;
if (!super.equals(o)) return false;
Genre genre = (Genre) o;
return time == genre.time;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), time);
}
}
class Bid extends Video {
private String bidName;
public Bid(String name, String genre, String bidName, long viewCount, short rating) {
super(name, genre, viewCount, rating);
this.bidName = bidName;
}
public String getBidName() {
return bidName;
}
public void setBidName(String bidName) {
this.bidName = bidName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Bid)) return false;
if (!super.equals(o)) return false;
Bid bid = (Bid) o;
return Objects.equals(bidName, bid.bidName);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bidName);
}
}
class RadioStation {
private List<Genre> genres;
private List<Bid> bids;
private List<Video> videos;
public RadioStation() {
this.genres = new ArrayList<>();
this.bids = new ArrayList<>();
this.videos = new ArrayList<>();
}
public void addGenre(Genre genre) {
genres.add(genre);
}
public void addBid(Bid bid) {
bids.add(bid);
}
public void addVideo(Video video) {
videos.add(video);
}
public List<Genre> getGenres() {
return genres;
}
public List<Bid> getBids() {
return bids;
}
public List<Video> getVideos() {
return videos;
}
}
Таким образом, у класса Genre и Bid общий родитель Video, и дублирующиеся поля перемещены в класс Video. Это оптимизирует код и делает его более структурированным.
Если вы не хотите использовать наследование для связывания классов, вы можете использовать композицию. Это тоже хороший подход, особенно когда наследование не подходит для вашей архитектуры.
На примере вашего кода можно сохранить текущую структуру классов, но всё равно необходимо обеспечить более эффективное распределение обязанностей и уменьшить дублирование кода. Вот версия с использованием композиции:
Композиция: Вместо использования наследования, вы чётко разделяете ответственность классов, но можете использовать другие способы связать их, например, через интерфейсы или ассоциацию.
Убраны дублирующиеся поля: Вы переписали Genre и Bid, чтобы сохранять общую функциональность без использования наследования.
Вот как может выглядеть переработанный код:
java
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RadioStationDemo {
public static void main(String[] args) {
Genre genreVideo = new Genre("MACAN - TSM", "Rap", 3, 5, (short) 40);
Bid bid = new Bid("FRIENDLY THUG 52 NGG - AMMO", "Underground rap", "Street racing", 32, (short) 35);
RadioStation radioStation = new RadioStation();
radioStation.addGenre(genreVideo);
radioStation.addBid(bid);
System.out.println("Genre Information:");
System.out.println("Video Name: " + genreVideo.getVideoDetails().getName());
System.out.println("Genre: " + genreVideo.getVideoDetails().getGenre());
System.out.println("Time: " + genreVideo.getTime() + " min");
System.out.println("View Count: " + genreVideo.getVideoDetails().getViewCount());
System.out.println("Rating: " + genreVideo.getVideoDetails().getRating());
System.out.println("Bid Information:");
System.out.println("Bid Name: " + bid.getBidName());
System.out.println("Bid Video Name: " + bid.getVideoDetails().getName());
System.out.println("Bid Genre: " + bid.getVideoDetails().getGenre());
System.out.println("Bid View Count: " + bid.getVideoDetails().getViewCount());
System.out.println("Bid Rating: " + bid.getVideoDetails().getRating());
genreVideo.setTime(2);
bid.setBidName("Overnight in St. Petersburg");
System.out.println("Updated Genre Time: " + genreVideo.getTime() + " min");
System.out.println("Updated Bid Name: " + bid.getBidName());
}
}
class VideoDetails {
private String name;
private String genre;
private long viewCount;
private short rating;
public VideoDetails(String name, String genre, long viewCount, short rating) {
this.name = name;
this.genre = genre;
this.viewCount = viewCount;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public long getViewCount() {
return viewCount;
}
public void setViewCount(long viewCount) {
this.viewCount = viewCount;
}
public short getRating() {
return rating;
}
public void setRating(short rating) {
this.rating = rating;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VideoDetails)) return false;
VideoDetails that = (VideoDetails) o;
return viewCount == that.viewCount &&
rating == that.rating &&
Objects.equals(name, that.name) &&
Objects.equals(genre, that.genre);
}
@Override
public int hashCode() {
return Objects.hash(name, genre, viewCount, rating);
}
}
class Genre {
private VideoDetails videoDetails;
private int time;
public Genre(String name, String genre, int time, long viewCount, short rating) {
this.videoDetails = new VideoDetails(name, genre, viewCount, rating);
this.time = time;
}
public VideoDetails getVideoDetails() {
return videoDetails;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Genre)) return false;
Genre genre = (Genre) o;
return time == genre.time &&
Objects.equals(videoDetails, genre.videoDetails);
}
@Override
public int hashCode() {
return Objects.hash(videoDetails, time);
}
}
class Bid {
private VideoDetails videoDetails;
private String bidName;
public Bid(String name, String genre, String bidName, long viewCount, short rating) {
this.videoDetails = new VideoDetails(name, genre, viewCount, rating);
this.bidName = bidName;
}
public VideoDetails getVideoDetails() {
return videoDetails;
}
public String getBidName() {
return bidName;
}
public void setBidName(String bidName) {
this.bidName = bidName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Bid)) return false;
Bid bid = (Bid) o;
return Objects.equals(videoDetails, bid.videoDetails) &&
Objects.equals(bidName, bid.bidName);
}
@Override
public int hashCode() {
return Objects.hash(videoDetails, bidName);
}
}
class RadioStation {
private List<Genre> genres;
private List<Bid> bids;
public RadioStation() {
this.genres = new ArrayList<>();
this.bids = new ArrayList<>();
}
public void addGenre(Genre genre) {
genres.add(genre);
}
public void addBid(Bid bid) {
bids.add(bid);
}
public List<Genre> getGenres() {
return genres;
}
public List<Bid> getBids() {
return bids;
}
}
В этом варианте создается класс VideoDetails, который содержит общие данные о видео. Каждый из Genre и Bid хранит экземпляр VideoDetails, что устраняет необходимость дублирования полей и приводит к более чистому решению.
Если класс RadioStation был создан исключительно как контейнер для связывания других сущностей, и его функция ограничивается только хранением списков, то действительно, в данной архитектуре он может оказаться излишним. Часто такие посреднические классы нужны, если они несут дополнительную логику управления, например, фильтрацию, поиск и управление данными.
Если в текущем решении его функционал незначителен, и вы не планируете его расширять, вы можете от него отказаться и работать напрямую с коллекциями Genre, Bid и VideoDetails.
Вот как может выглядеть упрощённый код без класса RadioStation:
java
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RadioStationDemo {
public static void main(String[] args) {
// Работа с коллекциями без использования посреднических классов
List<Genre> genres = new ArrayList<>();
List<Bid> bids = new ArrayList<>();
Genre genreVideo = new Genre("MACAN - TSM", "Rap", 3, 5, (short) 40);
Bid bid = new Bid("FRIENDLY THUG 52 NGG - AMMO", "Underground rap", "Street racing", 32, (short) 35);
genres.add(genreVideo);
bids.add(bid);
// Вывод информации о жанре
for (Genre g : genres) {
System.out.println("Genre Information:");
System.out.println("Video Name: " + g.getVideoDetails().getName());
System.out.println("Genre: " + g.getVideoDetails().getGenre());
System.out.println("Time: " + g.getTime() + " min");
System.out.println("View Count: " + g.getVideoDetails().getViewCount());
System.out.println("Rating: " + g.getVideoDetails().getRating());
}
// Вывод информации о заявках
for (Bid b : bids) {
System.out.println("Bid Information:");
System.out.println("Bid Name: " + b.getBidName());
System.out.println("Bid Video Name: " + b.getVideoDetails().getName());
System.out.println("Bid Genre: " + b.getVideoDetails().getGenre());
System.out.println("Bid View Count: " + b.getVideoDetails().getViewCount());
System.out.println("Bid Rating: " + b.getVideoDetails().getRating());
}
// Обновление информации
genreVideo.setTime(2);
bid.setBidName("Overnight in St. Petersburg");
System.out.println("Updated Genre Time: " + genreVideo.getTime() + " min");
System.out.println("Updated Bid Name: " + bid.getBidName());
}
}
class VideoDetails {
private String name;
private String genre;
private long viewCount;
private short rating;
public VideoDetails(String name, String genre, long viewCount, short rating) {
this.name = name;
this.genre = genre;
this.viewCount = viewCount;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public long getViewCount() {
return viewCount;
}
public void setViewCount(long viewCount) {
this.viewCount = viewCount;
}
public short getRating() {
return rating;
}
public void setRating(short rating) {
this.rating = rating;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof VideoDetails)) return false;
VideoDetails that = (VideoDetails) o;
return viewCount == that.viewCount &&
rating == that.rating &&
Objects.equals(name, that.name) &&
Objects.equals(genre, that.genre);
}
@Override
public int hashCode() {
return Objects.hash(name, genre, viewCount, rating);
}
}
class Genre {
private VideoDetails videoDetails;
private int time;
public Genre(String name, String genre, int time, long viewCount, short rating) {
this.videoDetails = new VideoDetails(name, genre, viewCount, rating);
this.time = time;
}
public VideoDetails getVideoDetails() {
return videoDetails;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Genre)) return false;
Genre genre = (Genre) o;
return time == genre.time &&
Objects.equals(videoDetails, genre.videoDetails);
}
@Override
public int hashCode() {
return Objects.hash(videoDetails, time);
}
}
class Bid {
private VideoDetails videoDetails;
private String bidName;
public Bid(String name, String genre, String bidName, long viewCount, short rating) {
this.videoDetails = new VideoDetails(name, genre, viewCount, rating);
this.bidName = bidName;
}
public VideoDetails getVideoDetails() {
return videoDetails;
}
public String getBidName() {
return bidName;
}
public void setBidName(String bidName) {
this.bidName = bidName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Bid)) return false;
Bid bid = (Bid) o;
return Objects.equals(videoDetails, bid.videoDetails) &&
Objects.equals(bidName, bid.bidName);
}
@Override
public int hashCode() {
return Objects.hash(videoDetails, bidName);
}
}
В этом варианте вся работа с объектами Genre и Bid осуществляется через коллекции в main методе. Это решение будет чуть менее удобным, если в будущем вам потребуется добавить больше логики. Если класс RadioStation всё-таки выполнял роль промежуточной бизнес-логики (например, мог работать с жанрами и заявками более структурированно), возможно, стоит его оставить.
у меня есть пример как должен выглядеть код: public class Main {
public static void main(String[] args) {
}
public class Shedule {
public Drug getDrug() {
return drug;
}
code
public void setDrug(Drug drug) {
this.drug = drug;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
private Drug drug;
private Patient patient;
private String adress = "City Centre";
private int time;
static String weather;
static int floor;
{
time = 20;
}
static {
weather = "Winter";
floor = 5;
}
public Shedule(Drug drug, Patient patient, String adress, int time, String w, int fl) {
this.drug = drug;
this.patient = patient;
this.adress = adress;
this.time = time;
weather = w;
floor = fl;
}
public Shedule() {
}
}
Ваш код содержит несколько классов с полями и методами экземпляра, а также статическими блоками и полями. На первый взгляд, код выглядит корректно и демонстрирует объектно-ориентированные концепции, такие как наследование и инкапсуляция. Тем не менее, есть несколько аспектов, которые стоит улучшить или изменить. Вот некоторые из них:
Конструктор MedicalPreparation(Drug drug, Patient patient): В данном конструкторе ничего не выполняется. Если он не нужен, лучше его удалить. Если он необходим для логики программы в будущем, добавьте его реализацию.
Статические поля: Использование статических полей вроде cost, wish, height, status и других может привести к проблемам с согласованностью данных между экземплярами, особенно если они позже изменяются. Лучше использовать нестатические поля для свойств, которые могут различаться между экземплярами.
Статические инициализаторы: Если поля имеют фиксированные значения и не должны изменяться, можно их инициализировать сразу при объявлении. Например:
java
static double weightBottle = 30.03;
static int count = 25;
Инициализация полей: Вместо использования инициализаторов блочного кода, инициализируйте поля при их объявлении, если значения известны на момент написания кода.
Архитектурный обзор: Если Scheduler должен работать с экземплярами Drug и Patient, возможно, стоит либо сделать поле в классе Patient типа List<Drug> или в классе Scheduler предусмотреть связь через какие-либо методы.
Вот улучшенная версия вашего кода:
java
public class Main {
public static void main(String[] args) {
Drug drug = new Drug();
System.out.println("Вывод: " + "{" + drug.getName() + ", " + drug.getIll() + ", " + Drug.cost + ", " + Drug.wish + "}");
Patient patient = new Patient();
System.out.println("Вывод: " + "{" + patient.getName() + ", " + patient.getSurname() + ", " + patient.getAge() + ", " + Patient.height + "," + Patient.status + "}");
Shedule schedule = new Shedule(drug, patient, "City Centre", 20, "Winter", 5);
System.out.println("Вывод: " + "{" + schedule.getDrug() + ", " + schedule.getPatient() + ", " + schedule.getAdress() + ", " + schedule.getTime() + ", " + Shedule.weather + ", " + Shedule.floor + "}");
MedicalPreparation preparation = new MedicalPreparation(drug, patient);
System.out.println("Вывод: " + "{" + preparation.getName() + ", " + preparation.getIll() + "," + preparation.typeOfProduct + ", " + MedicalPreparation.weightBottle + ", " + MedicalPreparation.count +"}");
}
}
class MedicalPreparation extends Drug {
String typeOfProduct = "Таблетка";
private String name = "Парацетамол";
static double weightBottle = 30.03;
static int count = 25;
public MedicalPreparation(String name, String ill, String typeOfProduct, double wB, int ct) {
super(name, ill, cost, wish);
this.typeOfProduct = typeOfProduct;
this.name = name;
weightBottle = wB;
count = ct;
}
public MedicalPreparation(Drug drug, Patient patient) {
super(drug.getName(), drug.getIll(), cost, wish);
// использование drug и patient для настройки
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}
class Patient {
private String name = "Иван";
private String surname = "Иванов";
private int age = 18;
static double height = 180.5;
static String status = "married";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Patient(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public Patient() {}
}
class Drug {
private String name = "Пенициллин";
private String ill = "Головная боль";
static double cost = 1440.1;
static boolean wish = true;
public Drug(String name, String ill, double c, boolean w) {
this.name = name;
this.ill = ill;
cost = c;
wish = w;
}
public Drug() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIll() {
return ill;
}
public void setIll(String ill) {
this.ill = ill;
}
}
class Shedule {
private Drug drug;
private Patient patient;
private String adress = "City Centre";
private int time = 20;
static String weather = "Winter";
static int floor = 5;
public Shedule(Drug drug, Patient patient, String adress, int time, String w, int fl) {
this.drug = drug;
this.patient = patient;
this.adress = adress;
this.time = time;
weather = w;
floor = fl;
}
public Shedule() {}
public Drug getDrug() {
return drug;
}
public void setDrug(Drug drug) {
this.drug = drug;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
Этот код следует тому же шаблону, но делает некоторые улучшения для обеспечения более надежного и чистого кода. Обратите внимание на использование нестатических полей там, где это возможно, и на сокращение количества пустых конструкторов и избыточных полей.
Для того чтобы адаптировать ваш предыдущий код в соответствии с предоставленным примером, мы будем следовать архитектуре и принципам, которые вы уточнили:
Удалим класс RadioStation, так как он не используется в вашем шаблоне.
Обеспечим взаимодействие между классами с использованием конструкторов и методов, как это задействовано в примере.
Настроим статические и нестатические поля и методы аналогично вашему шаблону.
Вот переработанный код:
java
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Video genreVideo = new Genre("MACAN - TSM", "Rap", 3, 5, (short) 40);
Video bidVideo = new Bid("FRIENDLY THUG 52 NGG - AMMO", "Underground rap", "Street racing", 32, (short) 35);
System.out.println("Genre Information:");
System.out.println("Video Name: " + genreVideo.getName() + ", Genre: " + genreVideo.getGenre() + ", View Count: " + genreVideo.getViewCount() + ", Rating: " + genreVideo.getRating());
System.out.println("Bid Information:");
System.out.println("Bid Name: " + ((Bid) bidVideo).getBidName() + ", Bid Video Name: " + bidVideo.getName() + ", Bid Genre: " + bidVideo.getGenre() + ", Bid View Count: " + bidVideo.getViewCount() + ", Bid Rating: " + bidVideo.getRating());
((Genre) genreVideo).setTime(2);
((Bid) bidVideo).setBidName("Overnight in St. Petersburg");
System.out.println("Updated Genre Time: " + ((Genre) genreVideo).getTime());
System.out.println("Updated Bid Name: " + ((Bid) bidVideo).getBidName());
}
}
class Video {
private String name = "Пенициллин";
private String genre = "Головная боль";
private long viewCount = 0;
private short rating = 0;
public Video(String name, String genre, long viewCount, short rating) {
this.name = name;
this.genre = genre;
this.viewCount = viewCount;
this.rating = rating;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getGenre() { return genre; }
public void setGenre(String genre) { this.genre = genre; }
public long getViewCount() { return viewCount; }
public void setViewCount(long viewCount) { this.viewCount = viewCount; }
public short getRating() { return rating; }
public void setRating(short rating) { this.rating = rating; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Video)) return false;
Video video = (Video) o;
return viewCount == video.viewCount && rating == video.rating && Objects.equals(name, video.name) && Objects.equals(genre, video.genre);
}
@Override
public int hashCode() {
return Objects.hash(name, genre, viewCount, rating);
}
}
class Genre extends Video {
private static int time;
static {
time = 5;
}
public Genre(String name, String genre, int time, long viewCount, short rating) {
super(name, genre, viewCount, rating);
Genre.time = time;
}
public int getTime() { return time; }
public void setTime(int time) { Genre.time = time; }
}
class Bid extends Video {
private String bidName;
public Bid(String name, String genre, String bidName, long viewCount, short rating) {
super(name, genre, viewCount, rating);
this.bidName = bidName;
}
public String getBidName() { return bidName; }
public void setBidName(String bidName) { this.bidName = bidName; }
}
Основные изменения:
Перенос кода из класса RadioStation напрямую в главный метод main класса Main, так как RadioStation был лишним.
Организация и инициирование объектов классов Genre и Bid в соответствии с вашим примером.
Устранение необходимости в классе-контейнере путем использования структуры данных и методов каждого из классов напрямую.