Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 months ago.
Improve this question
Its a cinema booking system. My system has 2 different types of Room (common room and 3D room) and a class of reservations (with name, age and date).
public class Room {
int number;
int capacity;
List<Reservations> reservation = new ArrayList();
// constructor
public Room(int number, int capacity, List<Reservations> reservation) {
this.number = number;
this.capacity = capacity;
this.reservation = reservation;
}
}
public class Reservations {
String name;
int age;
Date date;
public Reservations(String name, int age, Date date) {
this.name = name;
this.age = age;
this.date = date;
}
}
public class CommonRoom extends Room{
public CommonRoom(int number, int capacity, List<Reservations> reservation) {
super(number, capacity, reservation);
}
public class 3DRoom extends Room{
public 3DRoom(int number, int capacity, List<Reservations> reservation) {
super(number, capacity, reservation);
}
How can I make a reservation for Common Rooms and 3D Rooms? Because the list only store type Reservations, and I need to store CommonRooms and 3DRooms.
I suspect your question is too broad for Stack Overflow. But your code currently looks confused in terms of design so I'll offer some thoughts.
Firstly, why would the Room (the theatre where the films are screened) be responsible for handling its own reservations? Wouldn't it be better to have a BoxOffice class which handles the reservations for the whole cinema?
Secondly, what does a Room (theatre) actually need to do? If we move the handling of tickets to a BoxOffice, then keeping track of reservations would also be handled there. Each Room would just need to be able to return the name of the room, the capacity of the room, the seat map for the room (if you want to allow customers to pre-book a specific seat) and any special features (such as support for 3D movies, fancy surround sound, etc).
Thirdly, is there any real difference between a standard theatre and a 3D theatre in terms of your booking software? Probably not, and in fact a BoxOffice would need to be able to keep track of reservations, remaining capacity, and specific seat numbers still available, regardless of which type of theatre is being booked. (Don't forget that each theatre will show several different movie showings each day, so you'd need a MovieScreening type too which the BoxOffice links to reservations.) So there's probably no good reason to use inheritance to define Room and then CommonRoom and 3DRoom and it would be cleaner to simply have Room and use a name field and a supportedFeatures field to differentiate the different theatres in your cinema, allowing all of them to fit within the same List<Room> or Map<MovieScreening, Room> without worrying about the mess caused by subclasses.
If this is in fact just a homework exercise where your tutor is trying to get you to show off an example of using inheritance, then ignore all of this advice. But be aware that inheritance is more often a curse than a benefit, and there's usually a better way of structuring your type hierarchy.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hello so I'm having a bit of difficulties with a setter method on objects.
public class Company {
private String companyName;
public static int numberOfEmployees;
public Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
Employees employee1 = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());
employees[numberOfEmployees] = employee1;
numberOfEmployees++;
}
So basicly this is a method defined in the 'company class' while making an Employees object who's using the parameters for making a 'Programmer'.
But that's not the deal, what I want tot do is by calling this setter method, automaticly create an object. So each time it's used, kind of increment the name of the object it's going to make.
So for example the first time I use it it makes an object called Employee1 and stores it in Employee[0].. second time I want it to store Employee2 into Employee[1].
Maybe I'm making this way too difficult but I'm just trying things out, and can't seem to find a way to make this work.
I suppose that Programmer object is subclass of Employees, or else it will not work. More or less it should look like the following:
public class Company {
private String companyName;
public static int numberOfEmployees;
public static Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
numberOfEmployees++;
employees[numberOfEmployees] = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());;
}
As per requested by my instructor, we were asked to write a Surgery Room booking program as an assignment. He gave us the following breakdown:
A hospital contains a list (LinkedList) of rooms.
Each room contains a name (I set mine as a room number int) and a list (LinkedList) of bookings.
Each list (LinkedList) of bookings contains a start and end time (I set mines as Date) and a team (another LinkedList).
I've set my GUI and I have an idea of how to construct the methods, I'm just finding it difficult to start since I cannot place two pieces of information in one node (like, putting a name and a list of bookings for a particular room).
If it helps, I have a fully implemented:
LinkedList<T> extends AbstractSequentialList<T> implements List<T>, Deque<T>, Cloneable, Serializable
He gave us most of the code, but although it is mostly complete I'm still a little clueless.
Does anyone have any insight on how to deal with the LinkedList issue? Thanks!
Create a POJO, a class with two fields, and make your LinkedList of that POJO type. For example,
public class Room {
private final int number;
private final List<Bookings> bookings = new LinkedList<>();
public Room(int number) {
this.number = number;
}
public int getNumber() {
return this.number;
}
public List<Bookings> getBookings() {
return bookings;
}
}
And then, you can have a
List<Room> rooms = new LinkedList<>();
Above, creating Bookings with start and end Dates left as an exercise for the reader.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Im a new programmer and I want to know when its best practice to use overloaded constructors and what makes it different from single primary constructor.
The short answer is: you should use overloading whenever you need it.
As a real-life example, take a look at the JLabel API: https://docs.oracle.com/javase/8/docs/api/javax/swing/JLabel.html
JLabel has quite a few constructors: one that just takes a String, one that takes a String and an icon, one that only takes an icon, and one that doesn't take any arguments at all.
You would use each constructor when you want to construct that kind of JLabel: one that displays a String, one that displays a String and an icon, one that only displays an icon, or one that doesn't display anything yet (until you call one of its setter functions).
Constructor overloading is useful when you want to allow user to create objects in multiple different ways.For example to be able to create a simple Student class object in following different ways:
new Student(45); // given student id
new Student("name"); // given student name
new Student(45,"name"); // given student registration id and name
This helps ease the task of creating objects according to our requirements. You can link this concept with various java API's as the provide a no of different ways to initialize an object of a class.
Also you can combine the Construstor Overloading with Constructor chaining.
Here is an examlple:
public Student (int id){
this(id,"ANY-DEFAULT-NAME"); // calls the constructor of same class with 2 params
}
public Student (String name){
this(ANY-DEFAULT-ID,name);// calls the constructor of same class with 2 params
}
public Student (int id,String name){
// here you can initialize the instance variables of the class.
}
You can overload a constructor based in your needs. For example,let's say that you have a simple class called Dog, that have some attributes like: Name,Breed, Birthday, Owner and skin color.
public class Dog {
private String name;
private String breed;
private Date birthday;
private String owner;
private String skinColor;
/*Getters and Setters*/
...
}
If you instance a object of type Dog and want to set a all or some of the attributes' values, you'll have to call all the setters methods of the object, but with the constructor, you can save that step passing the values directly every moment you instance the object.
Example:
public class Dog {
private String name;
private String breed;
private Date birthday;
private String owner;
private String skinColor;
public Dog(String name, String breed,Date birthday,String owner,String skinColor){
this.name = name;
this.breed = breed;
this.birthday = birthday;
this.owner = owner;
this.skinColor = skinColor;
}
/*Getters and Setters*/
...
}
Dog myDog = new Dog("Jose", "Chiguagua",new Date(),"Jhon","Brown");
If you want only instance the object with the name only, you can do it too. A good practice is, if you have an object with attributes that is necessary to fill in some point, provide the default constructor, if you do not provide it, you will always need to pass some values for instance a object. This give flexibility to the programmer.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a problem in an exercise. The exercise is about teams. The user has to enter name and age of athlete, name and home of a team and name of the sport. when the user presses the "create athlete" button, a Joptionpane.inputdialog comes out to ask in what team he wants to place the athlete.
My problem is how to check if the team exists in arraylist teams, and how to place the athlete in that team.
if(e.getSource() == createAthlete){
String nameA = athleteName.getText();
Athlete A = new Athlete(nameA,Integer.parseInt(athleteAge.getText()));
String team= JOptionPane.showInputDialog("In what team do you want to place the athlete?);
}
public class Championship {
private String name;
private int durationMonths;
private static ArrayList<Championship> cship = new ArrayList<Championship>();
private static ArrayList<Club> clubs = new ArrayList<Club>();
public Championship(String name, int durationMonths){
this.name = name;
this.durationMonths = durationMonths;
}
public static void addChampioship(Championship c){
cship.add(c);
}
public static void addClub(Club club){
clubs.add(club);
}
}
It is quite urgent ,so thank in advance for your replies
clubs.contains(club) returns true if club is already there or false otherwise.
You just have to implement equals() for your data object (Club, Championship etc).
However if you need uniquness why not just to use set instead of list?
private static Collection<Club> clubs = new HashSet<Club>();
In this case even if you add the same club twice only one instance will present.
But in this case you should additionally implement hashCode() for your data objects.
BTW please pay attention on type that I used. You wrote ArrayList (i.e. concrete class at the left half of assignment. I wrote interface Collection that let me ability to easily change cocrete implementation (ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet etc) without affecting other code.
This isn't another how do I get an object from a collection. I have a predicament that is troubling me. I will do my best to explain the problem clearly.
I am working on a game, this game revolves around players looking after pets. I have decided it would be appropriate to have an arrayList of a players pets. (so an ArrayList allPets etc... in the players class)
My problem is when a player wants to do something with his/hers pets e.g. feed it how can I know exactly which index to use in the get method of the arrayList so I feed the correct pet?
This may be a simple problem but its confusing me, I am in the process of rigging up all the methods between player and pet but it dawned on me how will I actually know which pet object has been clicked. At the moment I have simply been passing in a pet object which I created for the purpose of testing the methods. That's not going to cut it when It comes to actual pet objects on the screen...
Any insight would be much appreciated!!
Give the Pet objects, a unique primary key. An integer ID field is popular, extremely efficient & sufficient to handle all but the largest transaction volumes.
Then, you can maintain a Map and efficiently get Pets by ID. This pattern can be used throughout your model.
With commercial applications backed by a SQL database, the similar pattern is used as well -- but retrieval is done via Hibernate.
Simple example:
public class Player {
protected List<Pet> petList = new ArrayList();
protected Map<Integer,Pet> petMap = new HashMap();
public List<Pet> getPets() {return petList;}
public Pet getPetById (int id) {return petMap.get( id);}
public void addPet (Pet pet) {
petList.add( pet);
petMap.put( pet.getId(), pet);
}
}
public class Pet {
protected int id;
// Id;
public int getId() {return id;}
// create; static factory.
//
public static Pet createPet() {
Pet pet = new Pet();
pet.id = KeyAllocator.alloc("pet");
return pet;
}
}
Hint: you can use LinkedHashMap to retain order of the Pets, without having to keep a List as well; but it changes getPets() return-type from List to Collection, which is a bit less nice.
KeyAllocator.alloc() enables you to re-use the allocation logic; basically it should start at 1 and increment inside a 'synchronized' block. (Avoid 0, since if you ever store your data with a persistence layer, 0 tends to mean 'new'.)