public static void main(String[] args) {
ReadAuthor ReadAuth = new ReadAuthor();
ReadCommands readCom = new ReadCommands(); }
In ReadARticles class I have a method for creating arraylist of articles.
public class ReadArticles {
public ArrayList<Article> articleList = new ArrayList<Article>();
while(i=0;i<line number;,++){
public void readDaFile(){
articleList.add( new Article(ID,name,publisherName,publishYear));
}
From ReadCommands class , I call ReadArt.readDaFile(reads but also creates arraylist).
public class ReadCommands {
ReadArticles readArt = new ReadArticles();
public void readDaFile(){
readArt.tryOpeningOrDieTrying(filename);
readArt.readDaFile(); }
My problem is ;from main ,I can reach articlelist by ;
System.out.println(readCom.readArt.articleList.get(20).getPublisherName());
or
System.out.println(readCom.getArticleList().size());
But I can not reach article list from readAuthor class(another class created for reading authors and creating arraylists for them.
I even tried creating getter for ArticleList in both ReadCommands and ReadArticles classes to make sure but getters work only for main. My aim is seeing articleList from ReadAuthor class.
ReadAuthor and ReadCommands are probably not in the same package.
Make ReadArticles readArt public in ReadCommands
Since there is no access modifier specified the default is "Package Protected".
You can read more about it here.
Related
I'm new to Java. I get this error when running the code below
Cannot make a static reference to the non-static field universityObj
But not getting error while using
University universityObj = new University();
The code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
University universityObj;
public static void main(String[] args)
{
University universityObj = new University();
universityObj.name="Robert";
universityObj.stuno=12;
System.out.println(universityObj.name);
System.out.println(University.university_name);
display();
}
public void nonStaticDisplay()
{
System.out.println(name);
System.out.println(stuno);
}
public static void display()
{
universityObj = new University();
System.out.println(universityObj.name);
}
}
Let's go step by step.
The display() method should be non-static because it belongs to and should be used on the specific instance of the University class. Static methods can be used without creating an instance of some class. But in the case of the display() method, it wouldn't makes sense to do that because you need to display the university name, which firstly should be created and assigned.
It's not a good idea to create the object instance University universityObj inside the class in your case. Better to leave it only in the main method.
The university_name name is not static, so you can't access it without the class instance (object) like you're doing right now. University.university_name should be changed to universityObj.university_name.
These steps will bring us to a such piece of code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
public static void main(String[] args) {
University universityObj = new University();
universityObj.name = "Robert";
universityObj.stuno = 12;
System.out.println(universityObj.name);
System.out.println(universityObj.university_name);
universityObj.display();
}
public void display() {
System.out.println(name);
System.out.println(stuno);
}
}
Other things, which you should consider:
Read about encapsulation.
Use code formatting in your IDE. Example for IntelliJ IDEA.
Check the toString() method from the Object class. It's intended exactly for what you're trying to achieve with your display() method.
You might simply pass a reference to the instance you want to be displayed. Like,
public static void display(University universityObj)
{
System.out.println(universityObj.name);
}
I do have one class that has one instance variable, that is being injected like below:
public Class HierarchyAccessor {
#Inject
HierarchyProvider provider;
public int GetAllHierarchies(HierarchyAccessorInput input) {
String requiredVariable = input.getId;
provider.provideHierarchy(requiredVariable);
}
}
Here, I do have another class HierarchyHelper, that has one static function which is performing some operation by creating an object of class HierarchyAccessor.
public Class HierarchyHelper {
public static List<String> getHierarchies() {
// Here I want to create the object of HierarchyAccessor.
// this is not working .
HierarchyAccessor accessor = new HierarchyAccessor();
/*
It performs some operations and returns the required output.
*/
}
}
So, here I'm unable to create the object of HierarchyAccessor class inside the static method, due to some constraint, I can't change this static method to non-static.
Can someone please suggest how to create the object of HierarchyAccessor inside the static method?
I'm learning to code java and I encountered some problems in which I could use help understanding how things work.
I've made a list containing "Images", on my Main class, called "myList".
public class Main{
public static void main(String[] args) {
List<Images> myList = new ArrayList<Images>();
...
And I want to access it on this "System" class. But it doesn't seem to let me.
The plan is to access a position (the 3rd, in this example) on the given list (list.get(2)).
So I created the method "work".
//Example
public class System{
public static boolean work(List<Images> list){
if( list.get(2).equals(Something) )
return false;
else ... return true;
}
On this same System class I'm trying to use the method "work", giving it the List that I created on my Main class (myList).
public class System{
...
if( work(myList) ) //Don't know how to reffer to myList
return something;
Gives me the error "myList cannot be resolved to a variable".
So the problem is how to reffer to the list I made on my Main, named "myList".
Not sure if I explained that too well but any suggestions?
Make a List a property of System class, then pass it in the constructor
public class System {
private List<Images> images;
public System(List<Images> images) {
this.images = images;
}
//your other methods
}
Ah, in your main you should also pass the list:
System system = new System(myList);
Another option its to make myList public static and access it like this:
Main.myList
Declare one helper class and declare your list with setter and getters. Mainatin a singleton object of this class and use that list then in different other classes.
you need to make sure its accessible.
Right now your list is scoped the main() function. which is static to boot.
You need to make it accessible. You can do this by storing it in a static variable and having a static function return it.
Or you pass the main object along to other object, so they can access it.
public class Main {
private List<Images> myList = new ArrayList<Images>();
public static void main(String[] args) {
new Main(args);
}
public Main(String[] args) {
myList.add('foo.png');
myList.add('bar.png');
System mySystem = new System(this);
}
public List<Images> getImages() {
return myList();
}
}
public class System{
Main global;
public System(Main main) {
global = main;
}
public void doSomething() {
Iterator<Images> it = global.getImages().iterator();
while(it.hasNext()) {
Images images = it.next();
}
}
}
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
}
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.