Always need to make static - java

I am working on a project, and I have come across something i do not fully understand yet.
Every time I like to call a method from another class, or use a variable from a jform my netbeans says that I need to make it "static". Now I understand what static means, and I have created objects from the class that I use methods from, but even then netbeans says that I need to make the object static before i can use it in the MAIN() method. Even the jform variables like comboboxes.
can somebody please explain this?
thanks in advance!
EDIT:
this is some code from my project. It's very small but it should clarify the problem:
the Mainclass:
public class SpeeloTheek {
/**
* #param args the command line arguments
*/
public static Controller MainController = new Controller();
public static SummaryScreen MainSummaryScreen = new SummaryScreen();
public static void main(String[] args) {
// TODO code application logic here
MainSummaryScreen.setVisible(true);
MainController.SetFullScreen(MainSummaryScreen);
MainController.ComboBoxItemSelected(SummaryScreen.choiceBox);
}
the controller class:
package speelotheek;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Controller {
//Method to make JFrame fullscreen//
public void SetFullScreen(JFrame frameToUse) {
frameToUse.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public void ComboBoxItemSelected(final JComboBox comboBoxToUse) {
comboBoxToUse.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
WhichSummary(comboBoxToUse);
}
}
});
}
public void WhichSummary(JComboBox comboBoxToUse) {
System.out.println(comboBoxToUse.getSelectedItem());
}
}
EDIT2:
Thanks all :) I found the problem. I instantiated the class in the main method instead above the main method and it worked :)

In order to call non-static members of a class you need to instantiate an object.
Example:
Foo myObject = new Foo(); // myObject is an object of class Foo
Foo.callToStaticMember(); // static members can be called using the class name
myObject.callToNonStaticMember(); // non-static members require an object of the class

This is because your main method is a static method.
From a static method you can't call the non static method's or variablen.
You need to change your main method to a constructor.
Then this code will be executed when you make an new instance of this class.

If you're using Netbeans GUI Builder, what you want to do is work from the constructor, instead of the main method
public NewJFrame() {
initComponent();
jComboBox1.addItem("Hello");
// do everything with your components here
}
All the objects declared by the GUI Builder are non-static. They're not meant to be accessed from the main.

if you are trying to access non-static methods from the main method. It would not work. The reason being, that static methods/variables do not belong to the instance of the class.
If you do need to access a non static method in your main method of another class. the only way to do it is through the instance of the class.
So, you would need to say
MyClass object = new MyClass();
object.aMethod();
EDIT
Do you want your application to be all static? Basically, static would mean that it will have only one memory location. So, for eg: if a user selects a radio button on one screen. it modifies the value in your code, and another user selects another radio button, it will overwrite the previous user's value.
What you do need to do is something like this.
public static void main(String[] args) {
// TODO code application logic here
Application appObject = new Application();
appObject.setController(new Controller());
appObject.setSummaryScreen(new SummaryScreen()); // Or pass these values through a constructor. Setters are just one way to do it. Or better yet, use Spring DI.
appObject.performAction();
}
public Class Application {
public Controller MainController ;
public SummaryScreen MainSummaryScreen ;
.... getters and setters of these instance variables.
public performAction(){
MainSummaryScreen.setVisible(true);
MainController.SetFullScreen(MainSummaryScreen);
MainController.ComboBoxItemSelected(SummaryScreen.choiceBox);
}
}

While you are working within the main method, which is static
public static void main(String[] args){
}
you can only call static elements, such classes, enum or static methods.
If you want to call a method member of a class from your main method, you have two options
Make the method static
class ClassA{
public static void methodOne(){
}
}
public static void main(String[] args){
ClassA.methodOne();
}
Instantiate the class in your main and call the non-static method.
class ClassA{
public void methodOne(){
}
}
public static void main(String[] args){
ClassA classA = new ClassA();
classA.methodOne();
}
Advice
You have to take care while using static methods, because they share its memory.
when you create a new class ClassA classA = new ClassA();, for each new class you create, it stores its own non-shared memory variables, but when you use static methods, they share the memory which could be dangerous.

Related

Unable to see ArrayList elements in another object in Java

I'm trying to view the elements of an ArrayList in a different class but it shows that there is nothing. In the other class, you can see the element in the ArrayList though.
Here are the codes.
First class
import java.util.ArrayList;
public class Test {
ArrayList<String> inventory = new ArrayList<String>();
public void test() {
inventory.add("item");
}
public void check() {
System.out.println(inventory);
}
}
Second class
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
System.out.println(testObj.inventory);
}
}
Main class
public class Main {
public static void main(String[] args) {
Test testObj = new Test();
Test2 test2Obj = new Test2();
testObj.test();
testObj.check();
test2Obj.test2();
}
}
Output
[item]
[]
In java Class level variables are Object associated until unless they are not declared static.
By means of Object associated is that when a object is initialized with new keyword in Java all Object will be having it's own memory and own class variables.
In your case inside main method when you create a Object of Test class and when you create a another test class object inside Test2 class, both will be totally independent of each other. And both will be having their own memory and own variables.
If you want that to get the updates of inventory variables from first object to be available in another object you need to declare it as static and should be initialized inside static block. Static variables are shared across all objects of class. As below:
static ArrayList<String> inventory;
static {
inventory = new ArrayList<String>();
}
In your main method, you call the method that handles adding operation yet you do not call any add methods in the second class and in your main method.
testObj.test();
testObj.check();
This one shows that you add an item into the arraylist and show it. But in the second class you do not add anything but calling it. Therefore there is no way to show any element from that method. What has should be done is that you just need to call the adding method inside of the second class and then try to use the display method.
You didn't call test() method in Test2 class.
To make it work change the Test2 class as follows.
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
testObj.test();
System.out.println(testObj.inventory);
}
}

Importing two utility classes with same name. Feature or useless?

For two utility classes with the same names, which contain only static methods, I proceeded as follows:
Simply imported the first
Created an instance of the second class.
Example:
package util1;
public class Utility {
public static void method() {
System.out.println("First Utility. static method");
}
}
package util2;
public class Utility {
public static void method() {
System.out.println("Second Utility. static method");
}
}
import util1.Utility;
public class Component {
private static final util2.Utility anotherUtility = new util2.Utility();
public static void usedByReflection() {
Utility.method();
anotherUtility.method();
}
}
Now I don't need to write a full second util-class name for invoke its methods, but maybe I did not foresee something...?
P.S:
The methods of the class Component are called through a reflection by a certain BlackBox. All the multithread-safe features are in BlackBox.
UPD: I have found better trick:
import util1.Utility;
public class Component {
private static final util2.Utility anotherUtility = null; // There are some changes
public static void usedByReflection() {
Utility.method();
anotherUtility.method();
}
}
Now I dont create new object, but is it possible to use it without any bugs?
IMO, this is confusing and could much more clearly be handled by something like:
public class CombinedUtilityComponent {
public static void usedByReflection() {
util1.Utility.method();
util2.Utility.method();
}
}
Or, better yet, in your code you can just fully qualify the class names and they become unique names without any confusing tricks.
Yes, this works. I wouldn't do it, though.
You're calling a static method as if it were an instance method. anotherUtility.method() has a useless reference to anotherUtility.
You also have an unnecessary instantiation of util2.Utility. This technique wouldn't work if the default constructor were disabled.

Recursive object access to private methods

Why does the following code print "YO"? Whose printYo() is being called? I would think that this code would not compile because printYo() is private to t.
public class Test {
private void printYo() {
System.out.println("YO");
}
public void doubleTrouble(Test t) {
t.printYo();
}
public static void main(String[] args) {
Test test = new Test();
test.doubleTrouble(new Test());
}
}
What can I do to make sure the outer object doesn't mutate the argument class?
printYo() is private to t
No. That method is private in regards to the class Test. Any piece of code within Test can use it.
What can I do to make sure the outer object doesn't mutate the argument class?
Java does not have any built in mechanism to refuse access to members on a per instance basis. (If that is what you meant.)
You are calling the method with in the class , which sound correct for the output . Even if you call the main method from different class it gives the same output.

<T> cannot be resolved to a type Java

I've got three classes:
One class which handles my main game operations. Its name is 'PlatformerGame'.
Note: Removed all game-related stuff.
public class PlatformerGame {
public PlatformerGame()
{
}
}
Then, I've got a class called 'PlatformerSingleton' which is meant to provide exactly one instance of the PlatformerGame.
public class PlatformerSingleton {
private static PlatformerGame game;
protected PlatformerSingleton()
{}
public static PlatformerGame getGame()
{
if (game == null)
game = new PlatformerGame();
return game;
}
}
And lastly, I've got the entry point of my application which is supposed to do nothing but get the instance of PlatformerGame and call its 'start' method.
public class Entry {
public static void main(String[] args) {
new PlatformerSingleton.getGame().start();
}
}
However, this is where the error happens:
What does this error mean and how can I prevent it? Also, are there any better approaches to implement this?
Note: I require access to the singleton instance from multiple classes, therefore I need this singleton class.
Don't add new in the line new PlatformerSingleton.getGame().start();
just change your line to:
PlatformerSingleton.getGame().start();
you are not creating new object here, you are just calling the static method of PlatformerSingleton class in which the object of the class is created using Singleton Design Pattern
Remove the new in that call:
new PlatformerSingleton.getGame().start();
Currently, it looks like you're trying to instantiate a class called PlatformerSingleton.getGame (a static nested class called getGame inside PlatformerSingleton).
You're looking for the static method inside PlatformerSingleton. Since it's static, you don't want to instantiate using new at all.
The compiler sees that the syntax is correct, but it doesn't find such class and thus throws an error. These kinds of errors are a bit tougher to correctly debug (as the actual error is syntactical), so you need to look a bit farther to fix it.
Just remove the newkeyword (you don't need new because you're creating PlatformerGameinstance inside of the getGame method):
public static void main(String[] args) {
PlatformerSingleton.getGame().start();
}
Since getGame() is a static method, you do not need to use the new keyword to call the method.
public static void main(String[] args) {
PlatformerSingleton.getGame().start(); // new keyword is not required
}
If getGame() was not static, only then it would have required an instance of PlatformerSingleton class for it to be called and that would have looked like
public static void main(String[] args) {
new PlatformerSingleton().getGame().start(); // if getGame() was a non-static method
}

How to run a package from another package inside the same project?

I have two packages inside my project, a and b.
a is my "main class" that runs when the program runs but I need to make b run from a (if that makes sense).
I'm sure its something along the lines of PackageB.BMain but I'm not sure.
Edit:
Okay so I've learned a few new things, to start my main project is RevIRC, inside that I have two packages, MainChat and RevIRC, now when I run the program RevIRC is ran, I need to make Mainchat run when RevIRC is ran.
Like I said before I'm sure its something along the lines of RevIRC.MainChat.ChatMain() but I can't seem to figure it out.
You have 2 options:
Either create a new instance of B from A, like so: PackageB.BMain b = new PackageB.BMain();
Access the methods in BMain in a static way like so: PackageB.BMain.someMethod();`
Note that you can use either of these exclusively or mix them up together, however, it all depends on how you have written your BMain class.
So for instance:
package PackageB
public class BMain
{
public BMain()
{ }
public void foo()
{
System.out.println("This is not a static method. It requires a new instance of BMain to be created for it to be called");
}
public static void bar()
{
System.out.println("This is a static method. It can be accessed directly without the need of creating an instance of BMain");
}
}
Then in your main class (the class which has the main method):
package PackageA
public class AMain
{
public static void main(String[] args)
{
PackageB.BMain.bar();
PackageB.BMain bInstance = new PackageB.BMain();
bInstance.foo();
}
}
If you have two main methods it will either run from A or B. The JVM will choose the first main method it sees IIRC.
Have a standalone class that will have main. And create your classes there.. ?
import a.Class1;
import b.Class2;
public class MainController
{
public static void main(String args[])
{
Class1 class1 = new Class1() ;
Class2 class2 = new Class2() ;
//Both class no start at the "same" time.
}
}
if i am not wrong you want to run main method of class B from class A.
That you can call using B.main(arg[]);
eg :
package a;
public class A
{
public static void main(String[] args)
{
System.out.println("This is main method of class A");
B.main(null);
/*pass any args if you want or simply set null arg*/
}
}
package b;
public class B
{
public static void main(String[] args)
{
System.out.println("This is main method of class B");
}
}
i hope this simple example will clear your doubt.
you can refer to link which contains Java tutorial for beginners.

Categories

Resources