Class instance assistance - java

I am working on a program that is supposed to implement an electronic store. I had to create 3 classes (desktop, laptop and fridge) with specific defined functionality which I did. I am stuck on how to create the Electronic store class in which the constructor for this class
must create three instances of each of the previous three classes (9 items in total, using the
constructors defined in those classes) and store them within the ElectronicStore instance being created. I am unsure on how to do the above and would appreciate assistance. Below is what I have gotten so far.
// Desktop class
public class Desktop{
double speed = 0;
int ram, storage = 0;
boolean storageType;
public Desktop(double s, int r, int p, boolean t){
speed = s;
ram = r;
storage = p;
storageType = false;
}
// This is a String representation of the Desktop object
//#Override
public String toString(){
return "#"+speed+"#"+ram+"#"+storage;
}
}
// Laptop class
public class Laptop{
double CPU;
int RAM, storage, size;
boolean storeType;
public Laptop(double C, int R, int st, int si){
CPU = C;
RAM = R;
storage = st;
size = si;
storeType = false;
}
// This is a String representation of the Desktop object
public String toString(){
return "#"+CPU+"#"+RAM+"#"+storage+"#"+size;
}
}
// Fridge class
public class Fridge{
double fridge;
boolean freezer;
String color;
public String toString(){
return "#"+fridge+"#"+color;
}
}
// ElectronicStore class (which i am stuck with)
public class ElectronicStore{
public ElectronicStore()
{}
}

You create an instance of a class like so:
Desktop desktopOne = new Desktop(x, y, z);
To store them you can either have class variables (like you have for speed, ram) etc., or you could use a data structure like a list. Further clarification needed on that point.

I think it should be something like this
public class ElectronicStore{
private ArrayList<Fridge> fridges = new ArrayList<>();
public ElectronicStore()
{
Fridge fridge1 = new Fridge();
Fridge fridge2 = new Fridge();
Fridge frigde3 = new Fridge();
fridges.add(fridge1);
fridges.add(fridge2);
fridges.add(fridge3);
...
}
}
And you have to do the same thing to create the other objects.

Related

How to deep copy an object array of multiple classes

As the title suggest, how do I do that? I have searched everywhere in the internet, maybe I didn't search for the right word or something. But please help me.
Object[] FlyingObject = new FlyingObject[3];
FlyingObject[0] = new Helicopter();
FlyingObject[1] = new Airplane();
FlyingObject[2] = new Drone();
Public static Object[] CopyFlyingObject(Object[] C){
Object FlyingObjectCopy = new Object(C.length);
// ...I got no idea how to continue from here
}
Using clone() is not allowed and you aren't allowed to find the name of the class either. I have copy constructor in my other classes but I have no idea how to call it when we're using object, especially with an object array with unknown classes throughout the array.
Edit:
My Subclass code
'''java
int speed;
double price;
Helicopter(){
speed = 0;
price = 0.0;
}
Helicopter(Helicopter c){
speed = c.speed;
price = c.price;
}
public Airplane extends Helicopter{
String brand;
Airplane(){
super();
brand = "";
}
Airplane(Airplane c){
super(C);
brand = c.brand;
}
public String getBrand(){
return brand;
}
}
public Drone{
//practically the same for here
}
'''

Better way to structure a java class with many variables

I have a java class called Player. The mechanics on how the player file interacts with the server would take a lot to explain and I have no issues with the file, I just want to improve it and better my programming skills. So my question is, how would I take the many variables I have, ints, strings, booleans and make the code faster and more efficient/cleaner. Here is an example so you can see what the file looks like
enter code here
public boolean usingGlory = false;
public int[] woodcut = new int [3];
public int wcTimer = 0;
public int[] mining = new int [3];
public int miningTimer = 0;
public boolean fishing = false;
public int fishtimer = 0;
public int fishXP;
public int fishies = 0;
public int fishreqt = 0;
public int fishitem = 0;
public int fishemote = 0;
public int fishies2 = 0;
public int fishreq2 = 0;
public boolean isfishing = false;
public boolean attemptingfish = false;
public int smeltType; //1 = bronze, 2 = iron, 3 = steel, 4 = gold, 5 = mith, 6 = addy, 7 = rune
public int smeltAmount;
public int smeltTimer = 0;
public boolean smeltInterface;
public boolean patchCleared;
public int[] farm = new int[2];
public boolean antiFirePot = false;
public boolean Lattack = false;
public boolean Lranged = false;
public boolean Lmagic = false;
public boolean Ldefense = false;
public boolean Lstrength = false;
public boolean Lspecial = false;
public boolean inPits = false;
public int pitsStatus = 0;
public boolean inFunPk = false;
public boolean InDung = false;
You can break down the data into several classes, each of which contains information on a specific area.
For example, here, you have a group of variables that are related to fishing - these can be grouped into e.g. a FishingComponent class. There's also a group of information on smelting that could be split into a SmeltingComponent class, and so forth. This may lead to making the code more readable by taking groups of closely related information and functionality into their own classes.
For reusability's sake, you may wish to use an entity component system. These are popular in games programming as they allow the makeup of objects to be customised more than just inheritance. If there is, for example, an NPC that may hold information on fishing but does not have stats, the fishing component may be added to the NPC entity, and all of the code relating to fishing may be re-used.
You also mention making the code faster - unless you have a specific performance problem, you are probably attempting to prematurely optimise. However, you may wish to look into pooling objects if they need to be garbage collected a lot, as in games written in garbage collected languages, garbage collection cycles can be one of the biggest cause of framedrops.
You might want to apply two common OOP techniques: encapsulation and composition. First of all, it's bad practice to have a bunch of public fields in your class. Instead, encapsulate them using getter and setter methods. Here's an example for the first two variables:
private boolean usingGlory = false;
public boolean isUsingGlory() {
return usingGlory;
}
public void setUsingGlory(boolean using) {
usingGlory = using;
}
private int[] woodcut = new int[3];
public int[] getWoodcut() {
return woodcut;
}
public void setWoodcut(int[] woodcut) {
this.woodcut = woodcut;
}
For more info, see Wikipedia.
The second technique is composition. You're right not to like having so many variables in your class. Instead of having all the variables be part of the Player class, group them into classes containing related items. You can even group methods, when appropriate! Here's an example that uses your fishing variables:
public class Player {
//...
private FishingState fishingState = new FishingState();
//Getter and setter
//...
}
public class FishingState {
private boolean fishing = false;
private int timer = 0;
private int XP;
private int fishies = 0;
private int reqt = 0;
private int item = 0;
private int emote = 0;
private int fishies2 = 0;
private int req2 = 0;
//Getters and setters
//A constructor and some methods:
public FishingState(int XP) {
this.XP = XP;
}
public void resetTimer() {
timer = 0;
}
}
Now, player.fishemote = 3 becomes player.getFishingState().setEmote(3). Longer, but clearer.

Problems writing and reading ArrayList<Object> with filestream in Java

In my Android application, I have a list of custom objects
ArrayList<Poke> pcList = new ArrayList<>();
Later in my code, I have save and load methods, that use Java OOS, and OIS to function. I have used these exact methods in other projects and know they work properly.
I believe I am having an issue with saving and loading a list of custom objects.
Here are the lines I'm calling to save, as well as load my list.
// save
oos.writeObject(pcList);
...
// load
pcList = (ArrayList<Poke>)ois.readObject();
Any ideas why I can't properly load/save with my list of custom objects?
Here is the interface that links a few similar objects:
public interface Poke {
int getNum();
String getName();
String getType();
int getValue();
boolean getShiny();
String getImageName();
}
Here is one of the similar object classes
public class BasicPoke implements Poke {
boolean shiny = false;
Random randomInt = new Random();
int iRandom = randomInt.nextInt(34 - 1) + 1;
int iShiny = randomInt.nextInt(31 - 1) + 1;
public int getNum(){
return this.iRandom;
}
public String getName(){
return this.pokeNames[iRandom-1];
}
public String getType(){
return this.pokeTypes[iRandom-1];
}
public int getValue(){
return 1;
}
public boolean getShiny() {
return (iShiny == 15);
}
public String getImageName() {
String threeDigitInteger = String.format(Locale.getDefault(),"%03d", this.getNum());
return (this.getShiny()) ? "icon"+threeDigitInteger+"s" : "icon"+threeDigitInteger;
}
String pokeNames = {"..","..",".."};
String pokeTypes = {"..","..",".."};
Please implement Serializable for the BasicPoke class. And by the way, could you tell us what issue (exception) when you load/save a list of objects?
Thanks,
Nghia

Java android multidimensional array (hash maybe) with string and nested class

I'm trying to track class stats for an android game I'm working on.
public static class characterClasses {
public String class_name;
public int base_hp;
public int base_attack;
public float base_defense;
}
I want to access these directly by name so I won't have to iterate over them repeatedly. From my research it looks like a hashmap or map would be what I need but everything I've seen is only for a single key/value pair. I need to access each stat value directly by class and value, something like
classList.get("warrior").get("base_hp");
Can someone point me in the right direction?
You are correct to think of using HashMap. You can use the characterClass String names as keys and the characterClasses as values. You can then use your getter methods to access your specific fields i.e.
classList.get("warrior").getBase_HP();
You could also forget maps entirely since these stats seem constant by using inheritance
public class Character {
int hp;
int attack;
int defense;
public Character (int hp, int attack, int defense) {
this.hp = hp;
this.attack = attack;
this.defense = defense;
}
public int getHP() {
return hp;
}
...
}
For your Character subclasses, you can preset those values in the constructor
public class Warrior extends Character {
public Warrior() {
super(2, 10, 8);
}
public int getHP() {
return super.getHP();
}
}
public class Wizard extends Character {
public Wizard() {
super(10, 3, 1);
}
public int getHP() {
return super.getHP();
}
}
This way all your Warrior and Wizard Objects will have the same stats that can be accessed any time simply by invoking their getters.

Calling a method from JFrame from another class

I am currently making a terrain generator, everything works fine in one class but I am going to be expanding my application.
Currently I have a JFrame class which holds everything, generating the terrain, painting the terrain, finding locations etc.
I want to add another class that will generate the terrain but when I create this class I need to access fields from the main JFrame class and when I do I get a stack overflow error - here is my code.
public class Simulator extends Applet
{
//fields
public Simulator()
{
grid = new int[100][100];
inhabGrid = new boolean[grid.length][grid.length];
gridSize = grid.length - 1;
dist = grid.length;
TerrainGenerator gen = new TerrainGenerator();
setSize(dist,dist);
seedGrid();
findInhabLocation();
printGridToConsole();
}
public void paint(Graphics g)
{
//panting the grid
}
public void seedGrid()
{
//seeding
}
public boolean generateTerrain(int x1,int y1, int x2, int y2)
{
//terrain generator
}
public boolean mouseUp(Event evt, int x, int y)
{
seedGrid(); //Create a new map
findInhabLocation();
repaint();
printGridToConsole();
return true;
}
public boolean keyEvents(Event evt, int x, int y)
{
seedGrid(); //Create a new map
findInhabLocation();
repaint();
printGridToConsole();
return true;
}
public void findInhabLocation()
{
//find best inhabitant location
}
public int locateWater(int x, int y)
{
//finding closest water
}
public int locateJungle(int x, int y)
{
//finding closest jungle
}
}
}
That works fine in its own class but when I create a class for example:
public class TerrainGenerator
{
Simulator sim = new Simulator();
}
I know this has something to do with the constructor and it's something silly I am doing, what would be the best way of splitting up this app into classes, for example terrain generator, inhabitants etc
For example I want to be able to call a method from the 'TerrainGenerator' class and call i.e. terrainGenerator.generateTerrain
Your TerrainGenerator creates a Simulator object and vice versa, hence you'll end up with infinitely many objects (but at some point the stack is full and a stack overflow exception is thrown instead...)
Instead of creating a new Simulator in your TerrainGenerator, you should pass a reference to your current Simulator (well, actually, that is not a great design either, but I'm not gonna confuse you with the problems of circular references).
Heuster answer is correct, furthermore, I think you could take look at MVC to help you organize your classes.
Depending which should be the parent, you can pass in the instantiated class to the other, ie;
private final TerrainGenerator gen; //if you need to save this.
public Simulator(TerrainGenerator terrainGenerator)
{
this.gen = terrainGenerator;
....etc
}
public class TerrainGenerator
{
Simulator sim = new Simulator(this);
}
or
private final TerrainGenerator gen; //if you need to save this.
public Simulator()
{
this.gen = new TerrainGenerator(this);
....etc
}
private final Simulator sim; //If you need to save it.
public class TerrainGenerator
{
public TerrainGenerator(Simulator simulator) {
this.sim = simulator;
}
}

Categories