Abstract object in constructor java - java

For a computer science project I have a Movie class that implements Comparable with Comedy, Action, and MovieTrilogy extending it. The problem I am having is that MovieTrilogy takes 3 Movie objects in the constructor. The MovieTrilogy class needs to have the Movie objects as instance variables which means I need to declare an abstract object. I belive what my teacher would want is to declare the MovieTrilogy object with Comedy and Action objects, but I would still need to store them as instance variables. How would I do this? The movie constructor as well as the MovieTrilogy class are atatched below.
public class MovieTrilogy extends Movie{
private Movie movie1;
private Movie movie3;
private Movie movie2;
public MovieTrilogy(Movie Movie1, Movie Movie2, Movie Movie3){
movie1 = Movie1;
movie2 = Movie2;
movie3 = Movie3;
}
And this is the movie class.
public abstract class Movie implements Comparable<Movie>{
private int Score;
private String Title;
public Movie(String title, int score){
Title = title;
Score = score;
}
public int getScore(){ return Score; }
public String getTitle(){ return Title; }
public int compareTo(Movie movie){
return this.compareTo(movie);
}
public String getGenre(){
return null;
}
public String toString(){
return Title + " with a score of " + Score;
}
}
The code below is the error it gives me trying to compile MovieTrilogy.
MovieTrilogy.java:5: error: constructor Movie in class Movie cannot be applied to given types;
public MovieTrilogy(Movie Movie1, Movie Movie2, Movie Movie3){
^
required: String,int
found: no arguments

Okay so first let me address your specific error. In order for MovieTrilogy to extend Movie it has to satisfy the constructor that you enforced in the Movie class. So in order to construct a Movie (and consequently a MovieTrilogy) you have to provide a title and a score via a super method in the constructor.
So something like this:
public MovieTrilogy(Movie Movie1, Movie Movie2, Movie Movie3) {
super("Trilogy title", 0);
movie1 = Movie1;
movie2 = Movie2;
movie3 = Movie3;
}
However I wonder whether it is a good idea for MovieTrilogy to extend a Movie, as a trilogy doesn't really represent a specific movie, so can't be expected to have the same properties a movie does. I would recommend researching into inheritance as a programming concept to get some more clarity on how you should be thinking about it.
From the fact your constructor takes title and score it seems like you might be trying to represent some form of media that is rated so maybe you could have a structure like this:
class RatedTitle(String title, int score);
class Movie(String title, int score) extends RatedTitle(title, score);
class MovieTrilogy(String title, int score, Movie[] movies) extends RatedTitle(title, score);
(I hope you can think of a much better name than RatedTitle)
Edit
As #JohnHenly pointed out and said so eloquently,
Movie#compareTo(Movie movie) is looking a little infinite.
You seem to have a misunderstanding of implementing the Comparable interface and at the moment using the comparison method will result in a StackOverflowException. By returning this.compareTo(movie) you are trying to call the compareTo method defined in Movie which will then attempt to return this.compareTo(movie) again and again until the JVM can't take it anymore.
There are many articles that explain how to override toCompare properly but you might want to read this one because of the amazing title: Add the Comparable flavor, and taste the feeling.

Related

Java object extensions

So i'm in the process of building a movie hiring system and have come to conclusion that I want to have a class of movies (which have specific movie data stored) and then another class which will have objects which extend the specific movies (eg, copies of Star wars: the new Hope) each with their own unique ID.
How do I setup my classes so that the information for each unique movie is inherited by the copy objects? (will extending my movieCopy class by my movies class achieve what I'm trying to do? Because I was thinking that would just extend the variables of the movie class, rather than the specific attributes of each object of the movie class.
Sorry in advance for any communication errors. Please feel free to ask if you need me to clarify something.
Structure I'm trying to achieve:
Movie (class)
MovieCopy(class)
MovieCopy <- attributes of the specific movie are inherited in each copy of the movie
Your MovieCopy class (DVD, Bluray, ...) could just contain a member variable storing the associated Movie instance (actual film with title, description, ...). That way you have access to all the meta data without any awkward inheritance.
class Movie {
private long id;
private String title;
private LocalDate release;
private String contentDescription;
Movie(long id, String title) {
this.id = id;
this.title = title;
}
...
}
class MovieCopy {
private long copyId;
private Movie movie;
private LocalDate lastHired;
private LocalDate latestReturn;
MovieCopy(long id, Movie movie) {
this.copyId = id;
this.move = movie;
}
...
}
EDIT - You would populate your collection of movies like this:
Movie starWars4 = new Movie(1, "Star Wars 4");
MovieCopy starWarsDvd1 = new MovieCopy(1, starWars4);
MovieCopy starWarsDvd2 = new MovieCopy(2, starWars4);
MovieCopy starWarsDvd3 = new MovieCopy(3, starWars4);
As a result you have three copies of the same Movie.
In your case, inheritance is not very suitable. What you are trying to do is create objects. You don't even need a MovieCopy class. You store the specific details of each movie in the movie objects.
Let's assume that your movie class has a name and a durationInMinutes fields and they both have getters and setters. If you want to create a new movie copy, you can do this:
Movie movie = new Movie ();
movie.setName("Star Wars");
movie.setDurationInMinutes (150);
And then you can refer to Star Wars using the variable name --- movie.
You might have other fields in your Movie class but you get the idea, right?
Let me show you when to use inheritance: if you have a kind of movie that has some attributes that ordinary movies don't have, which I can't give you an example because there is only one kind of movie.

Assigning enum to Items

Some background on the project: I am attempting to craft a space/sci-fi combat sim game with tabletop rpg style dice mechanics cranked up to 11 on the complexity scale, but still being transparent about the die rolls going on under the hood. I'm currently using the Star Wars Saga Edition combat rules as a basis.
Currently I'm trying to figure out a way to assign traits to vehicle.(possibly stored as a class for each vehicle) Each trait is an enum so that it can store multiple pieces of information. Here is the code I have for size categories:
public enum VehicleSize {
LARGE(1,"Speeder bike",5),HUGE(2,"Small Fighter",10),GARGANTUAN(5,"Tank, Medium Fighter",20),COLOSSAL(10,"Imperial Walker, Light Freighter",50),
COLLOSSALfrigate(10,"Corvette, Frigate",100),COLLOSSALcruiser(10,"Imperial-class Star Destroyer, Cruiser",200),
COLLOSSALstation(10,"The Death Star, Space Station",500);
private final int refMod;
private final int threshMod;
private final String desc;
VehicleSize(int reflexModifier,String example,int thresholdModifier)
{
refMod = reflexModifier;
desc = example;
threshMod = thresholdModifier;
}
public int getRefMod() {
return refMod;
}
public String getDesc() {
return desc;
}
public int getThreshMod() {
return threshMod;
}
}
My question is such: How do create vehicle profiles in such a way that I can assign this and similar enums as traits?
For practically all purposes, a field whose type is an enum class is no different than a field of any other object type, like Integer or String.
Create a private field, add a getter and setter, or if the field is final (likely in your case, because a vehicle instance can't change its type), add it as a constructor parameter and remo e the setter.
public class Vehicle {
private final VehicleSize vehicleSize;
// other fields
public Vehicle(VehicleSize vehicleSize) {
this.vehicleSize = vehicleSize;
}
public VehicleSize getVehicleSize() {
return vehicleSize;
}
// rest of class
}
There is nothing mysterious about an enum, other than the number of different instances of it are known at compile time (and a few more things, but nothing scary).
To add this into a class, you can use it like any user defined type.
public class MyClass {
private MyEnum myEnum;
}

How do you allow an object to use fields stored in another object?

Say you create a class called Album and a class called Song. You want Album objects to be able to use the fields stored within Song objects (for example, the song's filesize or runtime). What do you have to do to allow this to happen?
I've tried changing my fields within Song to public instead of private, but that hasn't worked. To be honest, I'm new to OOP and I think I'm overlooking something pretty fundamental here.
fields has to be private
that s why you can create accessors
getters and setters
see example :
Adding Setter and Getter Methods
To make the state of the managed bean accessible, you need to add setter and getter methods for that state.
Once the setter and getter methods have been added, the bean is complete. The final code looks like this:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Three ways:
Make the fields in question public. Not recommended, since it violates encapsulation
Provide "getter" methods in Song to return the values in question. The usual answer, sometimes also the correct one
Provide a method in Song to return a String representing the information you want. Useful if there's a complex of information that Song should be responsible for representing.
Generally speaking, I prefer to let objects "tend to their own knitting" as much as possible. To this end, I would always try to handle data in the class that owns it if it makes sense to do so. In this case, it makes sense for Album to compose the Song data into some presentable form, so I would suggest using getters in your song class to provide access, for example:
public int getFileSize(){
return fileSize;
}
public String getName(){
return name;
}
Then Album can put those together however it likes.
First of all, an Album would contain a list of songs.
For example :
public class Album
{
private List <Song> songs;
public Album ()
{
songs = new ArrayList <Song>();
}
}
Song would have public methods such as getName() and getLength(), which would allow an Album object to access them.
For example :
public int totalLength ()
{
int length = 0;
for (Song song : songs)
length += song.getLength();
return length;
}

how do I pass subclass parameters into the superclass private variables?

I am confused on how to get parameters from new object instances to also flow into the super class to update the private fields in teh super class.
So I am in an advanced Java class and I have homework that requires a "Person" Super Class and a "Student" subclass that extends Person.
The Person class stores the student name BUT it is the Student class constructor that accepts the Person name.
assume no method in Person to make a variable method update...like subClassVar = setSuperClassVar();
EX:
public class Person
{
private String name; //holds the name of the person
private boolean mood; //holds the mood happy or sad for the person
private int dollars; //holds their bank account balance
}
class Student extends Person //I also have a tutor class that will extend Person as well
{
private String degreeMajor //holds the var for the student's major they have for their degree
Public Student(String startName, int startDollars, boolean startMood, String major)
{
degreeMajor = major; // easily passed to the Student class
name = startName; //can't pass cause private in super class?
mood = startMood; //can't pass cause private in super class?
dollars = startDollars; // see above comments
// or I can try to pass vars as below as alternate solution...
setName() = startName; // setName() would be a setter method in the superclass to...
// ...update the name var in the Person Superclass. Possible?
setMood() = startMood; // as above
// These methods do not yet exist and I am only semi confident on their "exact"...
// ...coding to make them work but I think I could manage.
}
}
The instructions for the homework were a bit vague in terms of how much changing to the superclass of Person I am allowed to make so if you all believe a good solid industry accepted solution involves changing the superclass I will do that.
Some possible examples I see would be to make the private vars in Person class "protected" or to add setMethods() in the person class and then call them in the sub class.
I am also open to general concept education on how to pass subclass contstructor parameters to a super class...and if possible do that right in the constructor portion of the code.
Lastly, I did search around but most of the similiar questions were really specific and complicated code....I couldnt find anything straight forward like my example above...also for some reason the forum post did not clump all of my code together so sorry for the confusing read above.
Thanks all.
First, you need to define a constructor for Person:
public Person(String startName, int startDollars, boolean startMood)
{
name = startName;
dollars = startDollars;
mood = startMood;
}
Then you can pass data up from the Student constructor using super(...):
public Student(String startName, int startDollars, boolean startMood, String major)
{
super(startName, startDollars, startMood);
. . .
}
Alternatively, you can define setters in the Person class and invoke them from the Student constructor.
public class Person
{
private String name; //holds the name of the person
private boolean mood; //holds the mood happy or sad for the person
private int dollars; //holds their bank account balance
public void setName(String name) {
this.name = name;
}
// etc.
}

Java Linked List How to create a node that holds a string and an int?

I have been at this literally all day. I can create linked lists no problem and display/delete the data in them. My problem is though that I am not sure how to create a linked list of flights with each node including a reference to a linked list of passengers? This is an assignment in my advanced Algorithms class. I am drawing a blank here?
Create an object that holds a Passenger:
public class Passenger
{
private String name;
private int id;
}
Then give Flight a List of Passengers:
public class Flight
{
private List<Passenger> passengers;
}
Now you can have a List of Flights:
public class Schedule
{
private List<Flight> flights;
}
You needs lots more code in each. Be sure to override equals and hashCode for Passenger and Flight to make sure that they work properly.
Well, can't you just create a Flight class and a Passenger class?
class Flight {
private LinkedList<Passenger> passengers;
...
}
class Passenger {
...
}
LinkedList<Flight> flights = ...

Categories

Resources