r/javahelp • • Jul 28 '20

Warning when accessing static variable from a different class

Hello, I am doing a project where a class variable gets updated and that new value needs to go into a different class. The only way i was able to do this was by making it a static variable in its original class and then referencing it by className.staticVariable , but this gives me warnings in the IDE despite it working fine. I was wondering if theres a way to accomplish the same thing but without getting the warning, or if it is fine as it is. The warning reads : The static field className.staticVariable should be accessed in a static way. I have tried getting it to work by using object of the classes involved but these attempts just gave me overflow errors. Any help would be appreciated

0 Upvotes

10 comments sorted by

View all comments

1

u/Camel-Kid 18 year old gamer Jul 28 '20

to avoid using static variables, just pass in parameters to constructor and use the good ole getter/setters. Taht's what is so great about OOP design

1

u/Dead-Stroke54 Jul 28 '20

I tried doing this, but the issue is that the command is called without an abject it, so I can't actually edit the variables inside that object to then retrieve them from a different class. at least thats what i think is happeninng

1

u/Camel-Kid 18 year old gamer Jul 28 '20

well post your code

0

u/Dead-Stroke54 Jul 28 '20

This is what I have now: (Its for a minecraft plugin and the class I need )

package me.plugin;

import org.bukkit.Bukkit;

import org.bukkit.ChatColor;

import org.bukkit.command.Command;

import org.bukkit.command.CommandExecutor;

import org.bukkit.command.CommandSender;

import org.bukkit.entity.Player;

public class CommandListener implements CommandExecutor{

public static int time=5;

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){

if(sender instanceof Player){

if(label.equals("timeset") && args.length==1){

time= (Integer.parseInt(args[0]));

Bukkit.broadcastMessage("got here" + Integer.parseInt(args[0]));

Bukkit.broadcastMessage(ChatColor.BLUE + "Time set to " +args[0] + " seconds!");

}

return true;

} return true;

}

}

And int time is refferenced in MyListener by:

public static CommandListener cmd = new CommandListener();

public static int time = cmd.time;

Im pretty sure making an object of commandlistener is redundant but I didnt get around to make final changes yet.