An alternative to static classes - java

So I'm currently using a static class called GameFile and it holds the game instance, the current map, the player posiition, the player name, player money, etc. Basically all the global info. I was wondering if there is an alternative to this?
This is how I currently set in the static class the game instance (as an example):
GameFile.gameInstance = new ChromeGame();
and then when I need to use the information I call
GameFile.gameInstance.addScreen(SplashScreen).

This is how I would do it for a mobile game. You can have OOP concepts all through out and have all setters/getters, but in low type mobile devices, this "OOP" is costly.
public class GameData {
public static Model activePlayerModel;
public static GameMap currentMap;
public static void load () {
// read necessary data from external sources. e.g. a file
}
public static void updateMap () {
// update currentMap
}
public static Model getActiveModel() {
// get current model/set default/or read from file and return
}
public static GameMap getCurrentMap() {
// e.g. Create a map or read map from a file, etc
// return the map
}
}
Now I can access GameData's members directly.
public class GameScreen extends Screen {
Model playerModel;
public GameScreen (Game game) {
GameData.load();
playerModel = Settings.activePlayerModel;
}
}

Related

How to change and get objects from aother class without declaring it?

I am new to java. I try to get and change objects from a class ( ex: Class Camera or Class Microphone and objects camera1, camera2, camera3 , microphone1, microphone2, microphone3 in their classes each with price, name, score ) i want to get the name of one object and change one's price from another class without making a new one.
This is the first class:
public class Microphone{
String name;
int price;
/** Constructors, setters and getters */
Microphone mic1 = new Microphone("mic1",200);
Microphone mic2 = new Microphone("mic2",300);}
This is the second class:
public class Camera{
String name;
int price;
/** Constructors, setters and getters */
Camera cam1 = new Camera("cam1",500);
Camera cam2 = new Camera("cam2",1000);}
In the main class ( or in a different class like Shop, menu etc ) i want to get the price of one's object, like cam1.getPrice and mic2.setPrice so i can compare to the stats of the player in the game if he can afford it and to change the price of it.
You can create an ArrayList in your Main class with your object type and manage them this way. You can then modify your objects as much as you'd like. If you create an interface class you can do something like this:
First create the interface class, I named mine Device and gave it one method, to set the cost. You can add whatever methods you need to add, like setDate, setModel, setName.... etc
public interface Device
{
void setCost(double costIn);
}
Next create the microphone class and have it implement Device. After, you will need to add the Device methods to the class.
public class Microphone implements Device
{
double cost = 0.0;
public void setCost(double costIn)
{
cost = costIn;
}
}
Here is another class example with Camera, also with one data member.
public class Camera implements Device
{
double cost = 0.0;
public void setCost(double costIn)
{
cost = costIn;
}
}
Now in your main class, you can have all of your Devices into one ArrayList for easy manipulation and control.
public static void main(String[] args) throws FileNotFoundException
{
ArrayList<Device> arr = new ArrayList<Device>();
arr.add(new Microphone());
arr.add(new Camera());
}
Honestly there is a lot of ways to go about what you are asking, this is just one example.
Create a class(It is also known as model class) such as Car.
Then define relevent attributes inside that class.
Put the full args constructor.
Make setters & getters.
public class Car {
private String name;
Car(String name){
this name=name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
So you can change or get on created object using getters & setters.
example : Car c1= new Car("Audi"); If you want to change name of Car
c1.setName("Toyota");

Java Get the List of an Object from another Class

I'm having two classes : WorldOfRobots and Robot (abstract). Both are public. World of robots is basically an arraylist of Robot.
Then I have a class telebot which is an extension of Robot.
I'm trying to build a method in the class Telebot which will identify and get the list of robots where the current object Telebot is.
For example:
I create 2 World of Robots (wor1 and wor2) and then 1 telebot (r1).
I add r1 in wor1.
I'd like to get a way to get the list of robots of wor1 in a method of the class telebot.
Here is a bit of code.
abstract class Robot {
// content
}
public class Telebot extends Robot
{
// instance variables - replace the example below with your own
private WorldOfRobots wor;
public Telebot(String newName, String newDirection)
{
super(newName, newDirection);
}
public void something {
// here I'm trying to get the list
wor = new WorldOfRobots();
ArrayList<Robot> robots = wor.getList();
// Unfortunately this solution doesn't work cause I'm creating a new WOR. What I want is to get the WOR where the Telebot belong.
}
}
public class WorldOfRobots {
// List of robots
private ArrayList<Robot> robots;
public WorldOfRobots() {
robots = new ArrayList<Robot>();
}
public ArrayList<Robot> getList() {
return robots;
}
}
Thanks for your help.
You can refactor your class to something like this ...
public class Telebot extends Robot {
//your code and constructer here
public void something(WorldofRobots container){
//this is the list containing your instance of telerobot, use it as you like
}
}
Now from outside classes you can invoke robotInstance.something(listOfRobot);
I am not sure how your classes are exactly interacting so I cannot expand on using this method more.
abstract class Robot {
private WorldOfRobots world;
public void setWorld(WorldOfRobots world)
{
this.world=world;
}
// content
}
public class Telebot extends Robot
{
public Telebot(String newName, String newDirection)
{
super(newName, newDirection);
}
public void doSomething()
{
world.doSomethingElse();
}
}
public class WorldOfRobots {
// List of robots
private ArrayList<Robot> robots;
public WorldOfRobots() {
robots = new ArrayList<Robot>();
}
public void addRobot(Robot robot)
{
robots.add(robot);
robot.setWorld(this);
}
}
Storing a reference for the WorldOfRobots in the Robot class is reasonable in this case. If you want a robot to belong to multiple WorldOfRobots then change the world varible to List.

What is the best way to initialise static members before constructing objects in Java?

I am currently in the process of refactoring the code I wrote for a text/console version of the Mastermind board game. I am a bit stuck with how to best approach improving this section my GameLogic class.
public GameLogic(GameSettings gameSettings)
{
// ..other stuff..
// initialise static members
Board.setTotalRows(gameSettings.getNumOfGuesses());
Board.setTotalColums(gameSettings.getCodeLength());
// InputBoard and OutputBoard extends the abstract class Board
inputBoard = new InputBoard();
outputBoard = new OutputBoard();
}
What I am trying to do is set the static values of totalRows and totalColumns in the Board class BEFORE constructing the inputBoard and outputBoard objects. The reason why I want to do this is because I need to have these values present when constructing instances extending Board (an abstract class). The reason why I am making these values static is because they should be the same across all instances extending from Board and so that I can do something like Board.getTotalColumns() throughout the application.
The reason why I think this is suspiciously bad is because it would be possible to declare inputBoard or outputBoard without first setting the static member variables and of course it would also be possible to accidentally set the values of the static member later on to any arbitrary value.
Another approach I thought of was to make the getters in GameSettings public and static so that I could do something like this instead:
public abstract class Board
{
private static final int totalColumns = GameSettings.getCodeLength();
private static final int totalRows = GameSettings.getNumOfGuesses();
// other stuff...
}
This would allow me to avoid using setters and the problems associated with using them as listed above. But wouldn't this defeat the purpose of instantiating a GameSettings object?
What do you think are better alternatives to approach this?
I am not an expert on design pattern. I would try something like below -
Board.java
abstract class Board {
private final GameSettings gameSettings;
Board(GameSettings gameSettings) {
this.gameSettings = gameSettings;
}
public int getTotalColumns() {
return gameSettings.getCodeLength();
}
public int getTotalRows() {
return gameSettings.getNumOfGuesses();
}
//Other abstract methods
}
InputBoards .java
class InputBoards extends Board {
InputBoards(GameSettings gameSettings) {
super(gameSettings);
}
}
OutputBoards .java
class OutputBoards extends Board {
OutputBoards(GameSettings gameSettings) {
super(gameSettings);
}
}
GameSettings .java
class GameSettings {
public int getCodeLength() {
//return your value;
}
public int getNumOfGuesses() {
//return your value;
}
}
Now I would do -
public GameLogic(GameSettings gameSettings) {
inputBoard = new InputBoard(gameSettings);
outputBoard = new OutputBoard(gameSettings);
}

How do I make variables in a Main accessible to other classes?

For example I have a MovieDatabase class that contains a list of Movie objects. In my main code, I initialize all the objects in the MovieDatabase. However I wish to call this MovieDatabase in another class to access the library. How would I do this?
Do I add in get methods in my main code and return it? Or is there another way (eg. changing the list of objects to protected/public?)
Thanks!
Code's supposed to be 3 seperate classes, Main, MovieDatabase & Movie.
An instance of movieDatabase is initialized in Main. Upon construction, it calls loadMovieList() and populates the list from a text file. However I wish to call the same instantiation of movieDatabase from another class in order to access the movies, so that I do not have to repeat the loading.
public class Main {
public static void main(String[] args) {
MovieDatabase movieDatabase = new MovieDatabase();
}
public class MovieDatabase {
ArrayList<Movie>movieList = new ArrayList<Movie>();
String fileAddress = "D:/Users/Mine/School/Java/CZ2002_Assignment/src/MovieDatabase/movieDatabase.txt";
public MovieDatabase()
{
numOfMovie=0;
loadMovieList();
}
public int getNumOfMovie() {
return numOfMovie;
}
public void addMovieToList(Movie movie) {
movieList.add(movie);
numOfMovie++;
}
public Movie selMovieByID(int movieID) {
int index=-1;
for (Movie m : movieList) {
index++;
if (m.getMovieID() == movieID)
break;
}
return selMovieByIndex(index);
}
public Movie selMovieByIndex(int index) {
return movieList.get(index);
}
public void loadMovieList()
{
//loads through text file
addMovieToList(new Movie(tempMovie));
System.out.println("Movie Database loaded");
}
public class Movie{
private int movieID;
private String movieName;
private int movieDuration; //in minutes;
private String movieRating; //G; PG; PG13; NC16; M18; R21;
private boolean has3D;
private boolean status;
}
If you have a class that depends on a NameLibrary, you should inject it via the constructor or a set method.
Firstly, its difficult to assess what issues you truly have without any code to show us.
However you mention main method, as in
public static void main(String args[]){};
this main method is designed specifically to run the application, your compiler needs that specific method, it is not designed to be used as an accessor method
e.g.
public int getValue(){
return value;}
this is not the only reason you can't access the main method variable. main doesn't have a return type (due to the use of void) plus the idea of SCOPE (each method has a scope, any method that contains a variable can see that variable, but nothing outside of it can directly see it without a return type) you use scope to limit what can be accessed or what cannot be accessed outside of the methods or classes (thats why class variables usually will have private, in order to limit accessibility)
Create a getter-method which returns the list inside your NameLibrary. if your other class extends from NameLibrary you can call this getter-method with the object reference to your NameLibrary class.
If you want int x to be accessible from other classes, you write:
public class myClass{
public int x = 0;
}
To access it from other classes, you simply write:
myClass.x ... (do something)

Access a data from everywhere

I have a few frames in my program.I need to access a data from everywhere how can I do this?
public class Main{
public int aData;
public static void main(String[] args){
Frame1 f = new Frame1();
}
}
public Frame1 extends JFrame{
// ....
public void foo(){
// I need aData in here.
}
}
Edit 1 : I have more than one data and when one of them is updated the data in main class should be updated.
Just pass it in the Frame1 constructor
public class Main{
public int aData;
public static void main(String[] args){
Frame1 f = new Frame1(aData);
}
}
public Frame1 extends JFrame{
private int data;
public Frame1(int data) {
this.data = data;
}
// ....
public void foo(){
// use data here
}
}
The most important question is why you think you need to do this. If you truly want something accessible from anywhere, you can just make it a public static member somewhere, but this is horrible design practice.
Generally, you want to make your design modular, so each thing depends only on what it actually needs. Then you can pass it an object that provides the data it needs, such as configuration settings. This lets you mock things out easily for unit testing and the like, and reduces the amount of code you need to rewrite when making changes to the program.
Try making Fram1 instance static

Categories