Java - project, adding an object to class - java

I am currently struggling to figure out this problem for my project. I currently have a Food class that stores name, price and description with getters and setters and a toString. And a course class with subclasses (starter, main dessert). I am trying to figure out how to attach a Food to a Course.
public abstract class Course{
//fields
//protected only accessible to subclasses
protected MenuList starter;
protected MenuList main;
protected MenuList dessert;
protected MenuList drinks;
//Constructor
public Course(){
starter = new MenuList();
main = new MenuList();
dessert = new MenuList();
drinks = new MenuList();
}
//getters and setters
//methods
public abstract MenuList getList();
//add item
public void addItem(String course, String foodName, double price, String description, int calories){
this.addItem(course, foodName, price, description, calories);
}
}
starter subclass its the same with main and dessert subclasses
public class StarterFood extends Course{
//fields
//constructor
public StarterFood(){
//course,
starter.addItem("starter", "chicken wings", 2.30, "very nice", 150, false);
}
#Override
public MenuList getList() {
return starter;
}
//Constructors
//getters and setters
//methods
}
so far ive:
adding food (with a name, price, description, calories)
listing all food items
adding courses
searching for a course (by course number or name)
listing all courses
I only need to do this but I'm struggling any help is appreciated
attaching food to courses

If your trying to add a Food to a Course, you should use a "has a" relationship for example:
public class Course {
private Food food;
public Course(Food food) {
this.food = food;
}
public Course() {
}
public Food getFood() {
return this.food;
}
public void setFood(Food food) {
this.food = food;
}
}
I also wouldn't use StarterFood to extend a Course, because extends is for and "is a" relationship, I would call it StarterCourse and then add a default food for that course in the constructor.
public class StarterCourse extends Course {
public StarterCourse(Food food) {
// here call the super classes constructor
// add items via the Course constructor
super(food);
}
}
Then in your main class to test it out try this:
public class Main() {
public static void main() {
// First create new Food object
Food food = new Food();
// Create a new StarterCourse and add the Food object to it
StarterCourse starterCourse = new StarterCourse(food);
}
}

Related

Access instance of a class in another class

I'm very new to coding and have a strict deadline for this assignment so I couldn't find an explanation I understood very well so I am asking here.
I am makign an instance of my Pokemon class in a another class for my main game. I however need info on how many times a pokemon was defeated in my catch pokemon class as I want a user to only be able to catch a pokemon if they've beat it a certain amount of times. I have no clue how to do this however.
This is how the class is used if it is of any help:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Battle extends JFrame{
public Pokemon fire = new Pokemon("Charmander", "Fire");
public Pokemon water = new Pokemon("Squirtle", "Water");
public Pokemon plant = new Pokemon("Bulbasaur", "Grass");
public Pokemon ground = new Pokemon("X", "Ground");
I have tried something like Battle.pikachu.toString() in the main class to just test how to access it because that is what someone else told me but the battle part confuses me as I don't think it is actually referrign to anything when in my main class.
You should not define your Pokemon inside a Battle. You should instead pass your Pokemon into this Battle class.
So you should instead define your Pokemon in your Main class:
public class Main {
// Your functions...
private ArrayList<Pokemon> getMyPokemons() {
ArrayList<Pokemon> myPokemonList = new ArrayList<>();
Pokemon fire = new Pokemon("Charmander", "Fire");
Pokemon water = new Pokemon("Squirtle", "Water");
Pokemon plant = new Pokemon("Bulbasaur", "Grass");
Pokemon ground = new Pokemon("X", "Ground");
myPokemonList.add(fire);
myPokemonList.add(water);
myPokemonList.add(plant);
myPokemonList.add(ground);
return myPokemonList;
}
private void triggerBattle() {
ArrayList<Pokemon> myPokemonList = getMyPokemons();
Battle battle = new Battle(myPokemonList);
}
}
And in your Battle class,
public class Battle extends JFrame {
private ArrayList<Pokemon> myPokemons;
// Create constructor to receive your Pokemon
public Battle(ArrayList<Pokemon> myPokemons) {
this.myPokemons = myPokemons;
}
// And in other functions within this class, you can access
// myPokemons list
}
And of course if you need more information related to the Pokemon, you need to refer to #Boycpu suggestion and add more attributes to your Pokemon class.
Do you mean?
public class Pokemon {
private String name;
private String group;
private int defeatedTimes;
public Pokemon(String name, String group, int defeatedTimes) {
this.name = name;
this.pass = group;
this.defeatedTimes = defeatedTimes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getDefeatedTimes() {
return defeatedTimes;
}
public void setDefeatedTimes(int defeatedTimes) {
this.defeatedTimes = defeatedTimes;
}
}

Workaround implementation for "enum inheritance" in Java?

Preface: I've already researched why "enum inheritance" is illegal in Java.
My problem is the following: given a class Recipe, I want its property category to be a list of constant values like APPETIZER, BREAKFAST, DESSERT, MAIN_COURSE, SOUP - I logically use enums for this.
My question then is: if I wanted each of this enums to have "children of their own" (for example: SWEET and SAVORY for BREAKFAST, or CAKE, MUFFIN and BISCUITS for DESSERT), so that:
Specifying the subcategory ("child enum") is mandatory (e.g. myRecipe.setCategory(DESSERT) should raise an exception);
Using a "child enum" from a different "family" is forbidden (e.g. SOUP.BISCUITS should raise an exception);
I should be able to access the "child enum" through dot notation (e.g. myRecipe.setCategory(DESSERT.CAKE)) - or other similar "lightweight" syntax.
I haven't been able to come up with any clean solution in Java to fit all three requisites.
Is there any "esoteric" design pattern for this?
How would you implement this?
You can do this:
class Recipe {
private final Meal meal;
private final MealCategory category;
public <T extends Meal> Recipe(T meal, MealCategory<T> category) {
this.meal = meal;
this.category = category;
}
}
abstract class Meal {}
class Breakfast extends Meal {}
class Dinner extends Meal {}
class MealCategory<T extends Meal> {}
class Cereal extends MealCategory<Breakfast> {}
class Meat extends MealCategory<Dinner> {}
public class Test {
public static void main(String[] args) {
Recipe r = new Recipe(new Breakfast(), new Cereal());
Recipe r2 = new Recipe(new Breakfast(), new Meat()); // compile time error
}
}
Simple Design
Create a class Category. Inside Category, declare all the enum classes.
public class Category
{
public enum APPETIZER
{
}
public enum BREAKFAST
{
SWEET,
SAVORY
}
public enum DESSERT
{
CAKE,
MUFFIN,
BISCUITS
}
public enum MAIN_COURSE
{
}
}
Inside the Recipe class, category should be of type DESSERT. I have static imported Category class.
public class Recipe
{
DESSERT category;
public void setCategory(DESSERT category)
{
this.category = category;
}
public static void main(String[] args)
{
Recipe myRecipe = new Recipe();
myRecipe.setCategory(DESSERT.BISCUITS);
// statements below give compile time errors
// myRecipe.setCategory(DESSERT);
// myRecipe.setCategory(BREAKFAST.SWEET);
}
}
Improvement
Convert Category into a marker interface. All the categories such as DESSERT, BREAKFAST, etc. should implement Category.
interface Category {}
enum APPETIZER implements Category
{
}
enum BREAKFAST implements Category
{
SWEET,
SAVORY
}
enum DESSERT implements Category
{
CAKE,
MUFFIN,
BISCUITS
}
enum MAIN_COURSE implements Category
{
}
Make Recipe generic.
public class Recipe <T extends Category>
{
T category;
public void setCategory(T category)
{
this.category = category;
}
public static void main(String[] args)
{
Recipe<DESSERT> myRecipe = new Recipe<>();
myRecipe.setCategory(DESSERT.BISCUITS);
// statements below give compile time errors
// myRecipe.setCategory(DESSERT);
// myRecipe.setCategory(BREAKFAST.SWEET);
}
}
These are not design patterns. They are self implementation.

Inherited parent class values are not reflected in JPA save entity

I have a class Vehicle and Car
Vehicle extends Car
Lets take an example
Class Vehicle {
String vehicleMade;
boolean fourWheeler;
Vehicle(String vehicleMade, boolean fourWheeler) {
this.vehicleMade=vehicleMade;
this.fourWheeler=fourWheeler;
}
// getters and setters
}
Class Car extends Vehicle {
String model;
Car(String vehicleMade, boolean fourWheeler) {
super(vehicleMade, fourWheeler);
}
// getters and setters
}
Class JavaMainClass {
private static CarInfoRepository carInfoRepo;
private static AnnotationConfigApplicationContext ctx;
public static void main(String args[]) {
carInfoRepo= ctx.getBean(CarInfoRepository.class);
//Now where I have doubt and problem
Car carInfo = new Car("Bentley", true);
carinfo.setModel("Flying Spur");
log.debug(carInfo.getVehicleMade); // I get Bentley here
carInfoRepo.save(carInfo);
}
}
Now when I get the car object from the repo, I get vehicleMade and fourWheeler attribute as null
You can see when I get that vehicleMade before saving but after saving to the repo I am getting null as the attribute.

Need to code Manager and Employee classes. How do I make them "visible" to each other without breaking encapsulation?

The Manager and the Employee classes are both subclasses of EnterpriseMember. How do I write a "getManager" method (that returns the Manager instance that has this Employee in their List of reports) for the Employee class?
Thanks in advance!
public class Manager extends EnterpriseMember {
/*Fields */
private List reports = new ArrayList();
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public void addReport(Employee employee){
reports.add(employee);
}// How can "employee" know it is in this List?
}
public class Employee extends EnterpriseMember {
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return ???;
}
}
Something like this:
public class Manager {
private List<Employee> reports = new ArrayList<Employee>();
public void addReport(Employee e) {
if (e != null) {
this.reports.add(e);
e.setManager(this);
}
}
}
public class Employee {
private Manager manager;
public void setManager(Manager m) {
if (m != null) {
this.manager = m;
}
}
}
Just in case it's not clear, you should add all the other methods you need. I only illustrated how to update the Manager reference in Employee when it's added to the List of direct reports.
You should also have a removeReport method that removes an Employee from the List and sets its Manager to null.
How do you intend to find an Employee in this List? By name? Employee id? Hint: think about overriding equals and hashCode properly for your classes.
Aren't Managers also Employees? Don't bosses have bosses? This is a hierarchy, a tree.
Usually a Object with different Attributes looks like this:
public class Employee extends EnterpriseMember {
private Manager manager;
private String name; // You probably don't need this because you defined it in the Superclass.
.
.
.
/*Constructor */
public Employee(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return manager;
}
public void setManager(Manager manager){
this.manager = manager
}
// Other getters and setters for the attributes.
}

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");
}

Categories

Resources