Reputation: 894
I have an object declared in one class but now I am in another class and I want to get the field of the object without making everything static. In the current class I don't have the object which exists in the other class and I don't really understand how to call it. If i use a getter I guess I still need the object in the current class to call it, also I don't want to make the fields static, because I want the field unique for every object.
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();
}
}
thats how i created the 2 objects and set their fields trough a method. Now i am trying to use those 2 objects but in 3rd class
Upvotes: 0
Views: 106
Reputation: 12347
In your main class:
public class Main{
public static void main(String[] args){
Game game = new Game();
System.out.println(game.getCurrentDayOfWeek());
}
}
So you need to create the method getCurrentDayOfWeek.
You could make a singleton type pattern.
class Junk{
int value;
static Junk instance = new Junk();
static int getJunkStuff(){
return instance.value;
}
static void setInstance(Junk j){
instance = j;
}
}
It sounds like you should structure your code better, so maybe you should paste a more complete example.
A third class needs a reference to those objects? Then give it a reference.
class Third{
Game game;
public Third(Game g){
game = g;
}
public Third(){
}
public void setGame(Game g){
this.game = g;
}
}
So the third example, lets Third have a reference through a setter.
Upvotes: 1