我有一个在一个类中声明的对象,但现在我在另一个类中,我想获取对象的字段而不使所有内容都静态。在目前的课程中,我没有其他课程中存在的对象,我也不太懂得如何称呼它。如果我使用getter我想我仍然需要当前类中的对象来调用它,我也不想让这些字段保持静态,因为我希望该字段对每个对象都是唯一的。
package main;
import daysOfTheWeek.*;
public class Game {
private int currentDayOfWeek = 1;
private int totalDays = 1;
boolean playerHadEvent = false;
public void startGame(){
while(true){
boolean eventDay = false;
if(currentDayOfWeek == 5 || currentDayOfWeek == 6){ //check if current day isn't Friday or Saturday
eventDay = true;
}
System.out.println("==DAY " + totalDays + ", " + DaysOfTheWeek.getDay(currentDayOfWeek)+"==");
if(eventDay){
String event = Events.getEvent();
if(event.equals("gaming")){
System.out.println("Today there is " + Messages.getGamingEvent());
if(){ //get the field from another class's object
}
}
}
totalDays++;
currentDayOfWeek++;
if(currentDayOfWeek == 8){
currentDayOfWeek = 1;
playerHadEvent = false;
}
}
}
}
package main;
import daysOfTheWeek.*;
import dices.*;
public class Demo {
public static void main(String[] args) {
Student player = new Student();
Student computer = new Student();
player.generatePlayer(player);
computer.generateComputer(computer);
Game startingGame = new Game();
startingGame.startGame();
}
}
这就是我如何创建2个对象并通过方法设置它们的字段。现在我试图使用这两个对象,但在第三类
答案 0 :(得分:1)
在你的主要课程中:
public class Main{
public static void main(String[] args){
Game game = new Game();
System.out.println(game.getCurrentDayOfWeek());
}
}
所以你需要创建方法getCurrentDayOfWeek。
您可以制作单例类型模式。
class Junk{
int value;
static Junk instance = new Junk();
static int getJunkStuff(){
return instance.value;
}
static void setInstance(Junk j){
instance = j;
}
}
听起来你应该更好地构建你的代码,所以也许你应该粘贴一个更完整的例子。
第三类需要引用这些对象吗?然后给它一个参考。
class Third{
Game game;
public Third(Game g){
game = g;
}
public Third(){
}
public void setGame(Game g){
this.game = g;
}
}
所以第三个例子,让Third通过setter进行引用。