Passing to Setter and Getter methods - java

I have a Bread class and a Filling class which set the bread type and calories per slice as well as a filling class which sets the filling type and calories per serving... I can't seem to figure out how to pass them into the sandwich class correctly. My total calories doesn't work out
private class Sandwich {
private Bread bread;
private Filling filling;
private Bread caloriesPerSlice;
private Filling caloriesPerServing;
private Sandwich(String breadType, int caloriesPerSlice, String fillingType, int caloriesPerServing) {
setBread(bread);
setBread(caloriesPerSlice);
setFilling(caloriesPerServing);
setFilling(filling);
}
public Bread getBread() {
return bread;
}
public void setBread(Bread bread) {
this.bread = bread;
}
public Filling getFilling() {
return filling;
}
public void setFilling(Filling filling) {
this.filling = filling;
}
public int getTotalCalories(int caloriesPerSlice,int caloriesPerServing) {
(caloriesPerSlice) * 2 + caloriesPerServing = totalCalories;
return this.totalCalories;
}
}

You have your variable assignment backwards.
(caloriesPerSlice) * 2 + caloriesPerServing = totalCalories; is not valid. The variable being assigned to must be on the left.
Try:
totalCalories = (caloriesPerSlice) * 2 + caloriesPerServing;

(caloriesPerSlice) * 2 + caloriesPerServing = totalCalories; Doesn't do what you think it does.
Perhaps you mean
totalCalories = (caloriesPerSlice) * 2 + caloriesPerServing;

I see some problems in your code:
why does an instance of Sandwich should have two Bread object within? A sandwich is usually made by one type of bread.
the caloriesPerSlice and caloriesPerServing should be respectively attributes of Bread and Filling.
you can't pass a String parameter to setFilling(Filling filling) method.
(caloriesPerSlice) * 2 + caloriesPerServing is not a valid left-value and is not a valid expression because caloriesPerSlice and caloriesPerServing are objects.
This is a really basic implementation of your idea:
Bread.java
public class Bread
{
private String type;
private int caloriesPerSlice;
public Bread(String type, int caloriesPerSlice)
{
this.type = type;
this.caloriesPerSlice = caloriesPerSlice;
}
public String getType() { return type;}
public int getCaloriesPerSlice() { return caloriesPerSlice; }
public String toString()
{
return type + " (" + caloriesPerSlice + "cal)";
}
}
Filling.java
public class Filling
{
private String name;
private int caloriesPerServing;
public Filling(String name, int caloriesPerSlice)
{
this.name = name;
this.caloriesPerServing = caloriesPerSlice;
}
public String getName() { return name;}
public int getCaloriesPerServing() { return caloriesPerServing; }
public String toString()
{
return name + " (" + caloriesPerServing + "cal)";
}
}
Sandwich.java
public class Sandwich
{
private Bread bread;
private Filling filling;
public Sandwich(Bread bread, Filling filling)
{
this.bread = bread;
this.filling = filling;
}
public int getTotalCalories()
{
return 2 * bread.getCaloriesPerSlice() + filling.getCaloriesPerServing();
}
public String toString()
{
return "Bread: " + bread.toString() + "\nFilling: " + filling.toString();
}
}
Main.java
public class Main
{
public static void main(String args[])
{
Bread bread = new Bread("Baguette", 150);
System.out.println("I would like a " + bread.toString());
Filling filling = new Filling("Prosciutto di Parma", 75);
System.out.println("with " + filling.toString());
Sandwich sandwich = new Sandwich(bread, filling);
System.out.println("Your order is:");
System.out.println(sandwich.toString());
int totalCalories = sandwich.getTotalCalories();
System.out.println("The total calories are " + totalCalories);
}
}
This is the output:
I would like a Baguette (150cal)
with Prosciutto di Parma (75cal)
Your order is:
Bread: Baguette (150cal)
Filling: Prosciutto di Parma (75cal)
The total calories are 375

The class has a lot of errors:
You have a Bread caloriesPerSlice, but the constructor uses the same variable as int.
The same with the Filling caloriesPerServing and the int caloriesPerServing.
It has a private constructor. This constructor specify that the only way you can access a class of this type is through a static method in the class that returns an Sandwich object (like with the singleton pattern), which is not the case here.
The class is private: maybe I'm wrong, but a private class in java means that no one can access it.
The constructor: for example, breadType is a string object, and it's not used. You are trying to setBread with the private variable... what is that?
The constructor: caloriesPerSlice is an int type and you use it in the setBread() setter which receives a Bread type. You are mixing types.
The same with caloriesPerServing which is used in setFilling(), which receives a Filling object....
getTotalCalories: the assignment goes on the right, not the left.
I think you have a misunderstanding of OO. For example, let's see the Bread class:
If the bread class has the properties caloriesPerSlice and breadType they maybe are part of the bread type. Let's change the class to reflect those properties:
public class Bread {
private int caloriesPerSlice;
private String type;
public Bread(String type, int caloriesPerSlice)
{
this.type = type;
this.caloriesPerSlice = caloriesPerSlice;
}
public int getCaloriesPerSlice()
{
return this.caloriesPerSlice;
}
public String getType()
{
return this.type;
}
}
Here in this case the Bread is completely defined though his constructor. You can see that the class has no setter. That's because I decided it, but it's up to you if you want a parameterless constructor and setters in the class. Here in this case I only defined getters. Let's see the Filling class:
public class Filling {
private int caloriesPerServing;
private String type;
public Filling(String type, int caloriesPerServing) {
this.caloriesPerServing = caloriesPerServing;
}
public int getCaloriesPerServing()
{
return hits.caloriesPerServing;
}
public void setCaloriesPerServing(int calories)
{
this.caloriesPerServing = calories;
}
public String getType()
{
return this.type;
}
public void setType(String type)
{
this.type = type;
}
}
Here the Filling class has getters and setters. It's just for explanation purposes: in the Filling class you can set the properties through constructor or through the setters, whilst in the Bread you can only define the properties through the constructor.
Now the Sandwich maybe can receive all the properties that define a bread and a filling (like in your case), or maybe it can receive a bread and a filling). Let's see the first case:
public class Sandwich {
private Bread bread;
private Filling filling;
public Sandwich(String breadType, int caloriesPerSlice, String fillingType, int caloriesPerServing) {
this.bread = new Bread(breadType, caloriesPerSlice);
this.filling = new Filling(fillingType, caloriesPerServing);
}
public Bread getBread() {
return bread;
}
public void setBread(Bread bread) {
this.bread = bread;
}
public int getTotalCalories() {
return this.bread.getCaloriesPerSlice() * 2 + this.filling.getCaloriesPerServing();
}
}
As you can see, we received in the Sandwich constructor all the parameters which define a bread and a filling. Then, we created the Bread and Filling objects, passing their parameters. Finally, the getTotalCalories is nothing but a simple math of the bread and filling properties.
This code was just writen in a text editor. I did not checked if it's ok or not.
In this example, Sandwich becomes a class and a factory, a very important component of the class. As you can see, the construction of the Bread and Filling classes is made through the Sandwich. It has the advantage that the Sandwich controls the creation of objects, but the thing is: Is the sandwich responsible of that? Maybe not, because when you make a sandwich in your home you get the bread and the other ingredients and you just put them on the slices... the sandwich is not responsible of the creation of a bread slice... it does not make sense in the real life. Then, maybe it's a good idea to remove the object creation in the Sandwich constructor:
public Sandwich(Bread bread, Filling filling) {
this.bread = bread;
this.filling = filling
}
This case is more 'correct' because you're making a sandwich with the elements already generated in memory. It's the same when you make a sandwich in your home: you get the bread, the filling and then you make a sandwich.
I hope this can clarify a little more about OO.
Greetings!

Related

Object ArrayList For-Loop Error

I have an Object ArrayList and I need to use the toString() method of the Motor object, which is a parameter of the Vehicle object. My vehicle objects are in an ArrayList which is iterated through with a for-loop (I know a foreach loop would be easier, but this is part of the assignment)
Here is the code for the loop:
for (int i = 0; i < VehicleList.size(); i++) {
System.out.println();
String info = VehicleList.get(i).toString();
Motor m = VehicleList.get(i).motor;
String motorInfo = m.toString();
System.out.println(info);
System.out.println(m);
}
There is an error that says "motor cannot be resolved or is not a field".
All of the classes should allow this to work, unless of course there is a simple mistake I am missing.
Here is the Motor class:
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=
" + bhp + ", displacement= " + displacement;
}
}
Motors and Vehicles are intitialized here (In the TestVehicle class):
//Motors
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Motor Hemi = new Motor("Hemi", 8, 707, 5.7);
Motor P90D = new Motor("P90D", 0, 762, 0.0);
//Vehicles
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, 5, true, EcoBoost);
Vehicle v1 = new PassCar("Tesla", "Model S", 2016, 121000.0, 2, true, P90D);
Vehicle v2= new Truck("Dodge", "Ram", 2016, 46000.0, "pickup", 1500, Hemi);
PassCar and Truck are inherited classes of Vehicle with a few more attributes. I can post the PassCar or Truck class if needed but I do not think that is where the problem is arising from. I believe it is coming from the For-Loop, specifically the line Motor m = VehicleList.get(i).motor; but I am not sure of how to fix it.
Vehicle Class:
public class Vehicle {
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public void description() {
System.out.println("Description");
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
EDIT: There cannot be any Getters or Setters as per the assignment requirements, and it must be an ArrayList, not a regular List. When I switch to I get the error "Type mismatch: cannot convert from ArrayList to ArrayList
Here is an image of the classes:
ArrayList<Object> VehicleList = new ArrayList<>(Arrays.asList(vehicles));
VehicleList is declared to contain instances of Object, so the compiler will only let you access methods and fields it knows exist on all instances of Object.
Change it to ArrayList<Vehicle>.
First, mind the naming convention. Variables should be named in camcelCase e.g. vehicleListinstead ofVehicleList`
I have an Object ArrayList
I believe you mean declaration of vehicleList looks like ArrayList<Object> vehicleList
Then behavior is expected because compiler only knows that VehicleList.get(i) is going to return you an Object reference. It can be a Vehicle, but it can also be anything else. So it won't allow you to access the motor field, as there is simply no such field in Object.
Change your declaration to something like List<Vehicle> vehicleList
However, as mentioned in other answer, it is not a good idea to access the field directly because of various reason. A slightly less evil way is to have getter of motor. (A better way is to provide meaningful behaviors instead of providing access to internal data)
Create an interface IMotor which is used by Vehicle class and Implemented in PassCar and other implementation of vehicle.
IMotor.java
public interface IMotor {
public Motor getMotor();
}
Motor.java
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=" + bhp + ", displacement= " + displacement;
}
}
Vehicle.java
public abstract class Vehicle implements IMotor{
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
PassCar
public class PassCar extends Vehicle{
protected Motor motor;
public PassCar(String make, String model, int year, double price, Motor motor) {
super(make, model, year, price);
this.motor = motor;
}
public Motor getMotor() {
return motor;
}
}
Test.java
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, EcoBoost);
List<Vehicle> vehicles = Arrays.asList(v0);
System.out.println(vehicles.get(0).getMotor());
}
}
Your problem is that motor is not a member of the Vehicle class, but you are trying to access it through an expression of type Vehicle - namely vehicleList.get(i). This is forbidden, because the compiler has no way of knowing that every possible kind of Vehicle has a motor. After all, what would happen if you added a Bicycle class?
To make this work, you should remove motor from the Truck and PassCar classes, and add it to the Vehicle class. That way, vehicleList.get(i).motor would actually make sense, since the Vehicle expression would be guaranteed to refer to a Vehicle with a Motor.
It would also be recommended to use a getter for the motor field - that is, have motor as a private field of the Vehicle class, and write a method getMotor() to return it. You could then write vehicleList.get(i).getMotor() to get the Motor object associated with one Vehicle in the list.
Thanks to the help of all of your comments and my Java textbook, I managed to piece it together. Here is how I got it to work:
for (int i = 0; i < vehicleList.size(); i++) {
String motorInfo = "";
String info = "";
System.out.println();
if (vehicleList.get(i) instanceof PassCar) {
info = ((PassCar)vehicleList.get(i)).toString();
**motorInfo = ((PassCar)vehicleList.get(i)).motor.toString();**
}
else if(vehicleList.get(i) instanceof Truck) {
info = ((Truck)vehicleList.get(i)).toString();
**motorInfo = ((Truck)vehicleList.get(i)).motor.toString();**
}
Basically I had to use a polymorphic call and check if it was an instance of a PassCar or Truck.
And as for the Array and ArrayList used during the Class, I edited them like this:
Vehicle [] vehicles = new Vehicle [3];
vehicles[0] = v0;
vehicles[1] = v1;
vehicles[2] = v2;
showVehicle(vehicles);
ArrayList<Vehicle> vehicleList = new ArrayList<Vehicle>(Arrays.asList(vehicles));
System.out.println();
System.out.println("Output from ArrayList in main: ");
Thank you for the help everyone!

Implementing a Demo/Tester Program

I have a project for my java programming course.
The instructions are that we have to create a simple class and a tester class, and the class must include a Default constructor; Parameterized constructor with three parameters (make, model and price); Accessor method called getMake( ) to return the make; Accessor method called getModel( ) to return the model; Accessor method called getPrice( ) to return the price; Mutator method setMake( String newMake) to set the make; Mutator method setModel( String newModel) to set the model; and a Mutator method setPrice( double newPrice ) to set the price..
I have created my class and tester program, and my class compiles perfectly. When I try to run it, though get the error that there is no main method. Now, I followed my professor's example for the tester program and I get several errors on that. If anyone could give me the a pointer in the right direction, I would appreciate it.
My question is this: How do I implement my tester program? Do I need to create a zip file? I've tried doing so and didn't seem to help much...
The following is my code for the class:
public class Automobile
{
private String make;
private String model;
private double price;
public Automobile()
{
make = "Lexus2017";
model = "RX";
}
public Automobile(String initMake, String initModel, double initPrice)
{
make = initMake;
model = initModel;
price = initPrice;
}
public String getMake()
{
return make;
}
public String getModel()
{
return model;
}
public double getPrice()
{
return price;
}
public void setMake(String newMake)
{
make = newMake;
}
public void setModel(String newModel)
{
model = newModel;
}
Also, the following is my tester class(the one that has a lot of errors):
public class AutomobileTester
{
public static void main(String[] args)
{
Automobile make = new Automobile("Lexus 2017");
System.out.println("The car is " + make.getMake());
Automobile model = new Automobile("RX");
System.out.println("The car is " + Automobile.getModel());
Automobile price = new Automobile("43020");
System.out.println("The car is " + Automobile.getPrice());
// Use the mutator to change the make variable
Automobile.setMake("Lexus 2017");
System.out.println("The car is " + backDoor.getState());
// Use the mutator to change the model variable
Automobile.setModel("RX");
System.out.println("The car is called " + backDoor.getName());
Automobile.setPrice("43020");
System.out.println("The car is " + price.getPrice());
}
}
This is my first time working with constructors, and I'm very new to Java, so I'm sorry for any obvious errors. Thank you ahead of time for your time and help.
One of the first problems is that you do not use the proper number of parameters for your calls to the constructor, in Java (and most programming languages) you have to supply all of the required parameters to a method/function/constructor in one call. The fix for your code would be to use:
Automobile car = new Automobile("Lexus 2017", "RX", 43020.0D);
Also when you print out the cars information you first use an instance call then you use a static call, I won't go to much into the difference between the two but basically an instance call requires you to instantiate an object while a static does not. The fix for this problem would be to do:
System.out.println("The car is a " + car.getMake() + ", the brand is " + car.getModel() + ", the price is $" + car.getPrice());
As for changing the variables you should be using:
car.setMake("My New Car Make");
instead of:
Automobile.setMake("My New Car Make");
For the difference between static and instance you can look here, here, and here.
You did this correctly. You accessed the method by using the make instance variable of an Automobile class.
(side note: make is a bad name for an automobile instance, rather call it car1, or something)
Automobile make = new Automobile("Lexus 2017");
System.out.println("The car is " + make.getMake());
Now, everywhere else that you use Automobile.someMethod(), that's not right, because you need to set or get the data on one instance of the class, not the entire class.
Then, finally, you need to test the constructor with three parameters that you have in that class.
You have an error in the constructor call.
Your constructor takes three parameters (make, model and price) but when you call the method only send one. That is an error.
By default, the Java class constructor takes no parameters (in your case, this would be "new Automobile ()").
To implement the tester you have two options.
First, create the car using the constructor without parameters and then set the parameters:
Automobile auto = new Automobile();
auto.setMake("Lexus 2017");
auto.setModel("RX");
auto.setPrice(43020);
Automobile Automobile make = new Automobile ();
Another option is to use your own builder and pass parameters:
Automobile auto2 = new Automobile("Lexus 2017", "RX", 43020);
Automobile.java:
public class Automobile {
private String make;
private String model;
private double price;
public Automobile() {
}
public Automobile(String make, String model, double price) {
this.make = make;
this.model = model;
this.price = price;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
AutomobileTester.java:
public class AutomobileTester {
public static void main(String[] args) {
Automobile auto = new Automobile();
auto.setMake("Lexus 2017");
auto.setModel("RX");
auto.setPrice(43020);
System.out.println("The car1 is " + auto.getMake() + " " + auto.getModel() + " " + auto.getPrice());
Automobile auto2 = new Automobile("Lexus 2017", "RX", 43020);
System.out.println("The car2 is " + auto2.getMake() + " " + auto2.getModel() + " " + auto2.getPrice());
}
}

Intro to polymorphism 101 java

I'm making a small RPG. There is an Item class which is the parent of each item in the game. These items could be Potion (which is a class) or Bandage (which is a class).
The Item class looks like this:
public class Item
{
int qty;
String name;
Hero hero1;
public void passHero(Hero hero1)
{
this.hero1 = hero1;
}
public void use()
{
if(qty == 0)
{
System.out.println("You have no more of this item to use.");
}
else
{
qty--;
}
}
public void addInv(int value)
{
qty = qty + value;
}
}
A method for passing in the Hero class.
A method for using an item.
A method for adding to the inventory of the item.
This method activates these item classes:
public void initializeItemInventory()
{
items[0] = new Potion();
items[1] = new Bandage();
}
And this method would theoretically print all the items and their quantities:
public void useInventory()
{
for(int i = 0; i<items.length; i++)
{
System.out.println("Enter: " + i + " for " + items[i].name);
}
int response = input.nextInt();
items[response].use();
}
The Potion class, as an example, has an instance variable like:
String name = "Potion";
So my question. Why isn't the name variable from Potion being called correctly in the useInventory method. It returns null which tells me it's returning the parent class Item name, and not the name of the individual subclass variables.
public class Item
{
int qty;
String name;
...
The Item class already has name, and that's what you access from an Item-typed variable:
items[0].name
So if you have
public class Potion extends Item
{
String name = "Potion";
...
then the Potion class has two name fields:
Potion p = new Potion();
System.out.println(p.name);
System.out.println((Item) p).name);
As you say, you want polymorphism, but it only applies to methods. Therefore you need a getter:
public class Item
{
String name;
public String getName() { return name; }
...
In the Potion subclass you may have
public class Potion extends Item
{
public Potion() { this.name = "Potion"; }
...
and items[0].getName() will now work as expected.
Additional note
I'll add this to show a bit of the power of polymorphism.
If you happened to have the name property always the same for all the instances of the same class, you could easily refactor your getter-based solution by completely eliminating the need to store a name variable:
public class Item
{
public String getName() { return "Generic item"; }
...
public class Potion extends Item
{
#Override public String getName() { return "Potion"; }
...
Instead of declaring a new variable in your subclass like "String name = "Potion";"
Use your constructor to pass the value to your superclass, something like this:
// the Item supuerclass has one constructor
public Item(name) {
this.name = name;
}
// the Potion subclass has one constructor
public Potion() {
super("Potion");
}

Using Arrays.binarySearch on an array of Objects and looking for a String within the object

OK so I have the following Object class:
public class IntoleranceFood implements Comparable<IntoleranceFood>{
private int scoreInt;
public String foodName;
public IntoleranceFood(String food, int score) {
super();
this.foodName = food;
this.scoreInt = score;
}
//getters and setters
public String getFood() {
return foodName;
}
public void setFood(String food) {
this.foodName = food;
}
public int getScore() {
return scoreInt;
}
public void setScore(int score) {
this.scoreInt = score;
}
#Override
public String toString() {
return "Intolerance Food [Name=" + foodName + ", Score=" + scoreInt + "]";
}
#Override
public int compareTo(IntoleranceFood arg0) {
return toString().compareTo(arg0.toString());
}
}
And then in my Activity I have created an array for these objects to go into, and filled up the array with "IntoleranceFood" Objects:
int numFoodItemTypes = db.intoleranceFoodItemTypesTotal();
IntoleranceFood[] foodArray = new IntoleranceFood[numFoodItemTypes];
Cursor cAllFoodTypes = db.intoleranceFoodTypesList();
int foodItem = 0;
do{
foodArray[foodItem] = new IntoleranceFood(cAllFoodTypes.getString(0), 0);
foodItem++;
}while(cAllFoodTypes.moveToNext());
I managed to sort the array by implementing Comparable and the compareTo method in my Object class:
Arrays.sort(foodArray);
But I want to then search the array using binary search, and look for the position in the array where a certain Object with a specific food name (String) resides. But I dont know how to get the following code working, and specifically in terms of:
-binarySearch(Object[] array, Object value)
I don't know what to put in "Object value" so this:
Arrays.binarySearch(foodArray, "Cereal");
Is clearly wrong! But I'm not sure how to search the Object array for an Object containing the String food name "Cereal".
Thanks.
Yes so after the very useful reply below, I realsied what I need to be doing is:
IntoleranceFood searchOb = new IntoleranceFood("Cereal",0);
int searchIndex = Arrays.binarySearch(foodArray, searchOb);
And that works!
In my opinion your mistake is
Arrays.binarySearch(foodArray, "Cereal");
because "Cereal" is not the Object you are looking for and your array doesnt contain this object. The second parameter should be an instance of the IntoleranceFood class and "Cereal" is just a property of that class.
For your problem i would use a HashMap or another Map who fits your problem best!
Maybe this article will help you : How to sort a HashMap in Java

Storing multiple object types in a List

I have following homework about computer store:
There are several class include: Monitor, Case, Mouse, Keyboard.
All the classes have common fields: id, name, price, quantity.
Each class has some unique fields.
All most features are: add, update, delete, find, show list, save, load file
-So, first I will create a class named Product have 4 common fields. Above classes will extends from Product.
-Then, I think I maybe create a ComputerStore class which have a field is items type ArrayList. items stores all objects which are instance of 4 above classes But I'm not sure.
Whether it is reasonable? I need some ideas
Before , I always use ArrayList store for only one class like
List <String> list = new ArrayList<String>();
Now they are multi type. I think it's generic in Java, right??
In case, I want to update for 1 items. I must think about how to change information for them. Ex: mouse for some code, keyboard for another code. Anyway, thank for everybody!
Your approach is 100% reasonable.
You are completely on the right track with "generics". First, check out the official enter link description here.
Next, just think about your data in real world terms, like you are already doing: Monitor, case, mouse, and keyboard are products. Your computer store's inventory is a list of products.
Hint: A list of products.
Put that together with what you learn about generics through that tutorial, and you'll be good to go.
You could use java generic.First create a java collection (ex: List) with supper class type, Product. Now you could add any sub classes (Monitor , Keyboard etc) in your collection (List) that extends of class Product.
public class Product{
}
public class Monitor extends Product{
}
public class Keyboard extends Product{
}
List<Product> products = new ArrayList<Product>();
products.add(new Monitor());
products.add(new Keyboard());
Since you have a superclass (Product), you can have the list's type as Product, i.e.
List<Product> list = new ArrayList<Product>();
list.add(new Mouse());
list.add(new Keyboard());
It will allow you to iterate them and list their name and price without caring for the class, but if you intend to take an item out of the list you'll need to check its actual type (depending on what you do with it).
You can do like below
import java.util.List;
import java.util.ArrayList;
class Test{
public static void main(String... args){
List<MultiObj> multiObjs = new ArrayList();
MultiObj ob = new MultiObj(); multiObjs.add(ob);
ResX xOb = new ResX(); multiObjs.add(xOb);
ResY yOb = new ResY(); multiObjs.add(yOb);
ResZ zOb = new ResZ(); multiObjs.add(zOb);
for (int i = 0; i < multiObjs.size(); i++ ) {
System.out.println(multiObjs.get(i).getV());
}
System.out.println("Waoo its working");
}
}
class MultiObj{
public String greet(){
return "Hello World";
}
public String getV(){
return "Hello World";
}
}
class ResX extends MultiObj{
String x = "ResX";
public String getX(){
return x;
}
public String getV(){
return x;
}
}
class ResY extends MultiObj{
String y = "ResY";
public String getY(){
return y;
}
public String getV(){
return y;
}
}
class ResZ extends MultiObj{
String z = "ResZ";
public String getZ(){
return z;
}
public String getV(){
return z;
}
}
You could do this:
public class Item {
public Item(int id, string name, float price, int amount, int ArrayID) {
if (ArrayID == 1) {
ID1 = id;
name1 = name;
price1 = price;
amount1 = amount;
}
if (ArrayID == 2) {
ID2 = id;
name2 = name;
price2 = price;
amount2 = amount;
}
if (ArrayID == 3) {
ID3 = id;
name3 = name;
price3 = price;
amount3 = amount;
}
if (ArrayID == 4) {
ID4 = id;
name4 = name;
price4 = price;
amount4 = amount;
}
}
//ArrayID #1
public static int ID1;
public static String name1;
public static float price1;
public static int amount1;
//ArrayID #2
public static int ID2;
public static String name2;
public static float price2;
public static int amount2;
//ArrayID #3
public static int ID3;
public static String name3;
public static float price3;
public static int amount3;
//ArrayID #4
public static int ID4;
public static String name4;
public static float price4;
public static int amount4;
public static int[] id = ID1, ID2 ID3, ID4;
//so forth...
}

Categories

Resources