Java:具有一个类的多个对象 [英] Java: having multiple objects of one class
问题描述
我遇到一个问题,其中每个类都有多个对象,这是每个类创建的一堆对象,而且我遇到了错误.这4个类文件是Main,Game,Updates Building,我将展示每个类的构造函数,希望有人可以帮助我展示如何创建一个类的多个对象.我需要从更新和构建中访问游戏中的变量,但是当我尝试时会返回错误.如何从更新和构建中访问游戏中的变量
I am having an issue where each class has multiple objects, it is a mess of objects being created of each class and I am having errors. The 4 class files are Main, Game, Updates Building, I will show the constructors of each class and hopefully someone can help me show how to create multiple objects of one class. There are variables in game that I need to access from update and building but when I try errors are returned. How do I access the variables in game from both update and building
主要:
public class Main
{
public static void main(String[] args)
{
Game newGame = new Game();
newGame.setupGame();
Game.isRunning=true;
newGame.gameLoop();
}
}
游戏:
import java.util.Scanner;
public class Game {
private Scanner input;
private Updates getUpdates;
public Game(){
this.input = new Scanner(System.in);
this.getUpdates = new Updates(this);
}
int happyness;
double money;
int population = 1000000;
}
更新
import java.util.Scanner;
public class Updates {
private Scanner input;
private Game newGame;
Building buildBuilding = new Building();
public Updates(Game newGame){
this.newGame = newGame;
this.input = new Scanner(System.in);
}
}
建筑物
import java.util.Scanner;
public class Building {
public Building(){
this.input = new Scanner(System.in);
}
private Scanner input;
}
我希望建筑类能够访问main中的变量,而更新类则能够访问main中的变量.
I want the building class to be able to access the variables in main as well as the update class being able to access the variables in main.
推荐答案
更新类中的更改:
Building buildBuilding;
public Updates(Game newGame){
this.newGame = newGame;
this.input = new Scanner(System.in);
this.buildBuilding = new Building(newGame);
}
您不小心调用了一个空的构造函数,所以
You have accidentally called an empty constructor, so
public Building(Game newGame){
this.input = new Scanner(System.in);
this.newGame = newGame;
}
从未被调用过,因此input
为NULL.
was never called, and therefore input
was NULL.
这篇关于Java:具有一个类的多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!