This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 4 years ago.
My getter wants the method it's getting to have a static method but if I do that it will break my code is there any way around this?. Language Java.
This is the line in my test class that wants to get the method in my vending class.
System.out.println("Total Sales for both machines today $"+ VendingMachine.getTotalsSales());
This is my getter method that takes the array I created from the string provided in the test class that put the items into an array. I want to be able to keep this array that I have created while also getting the total sales.
public double getTotalsSales() {
totalSales += availableItems[this.selectItem].price;
return totalSales;
}
Is there any way I can keep my array and with also being able to grab the total sales from the tester class?
It sounds like VendingMachine is the name of your class, not the name of an instance of your class. Calling the method getTotalsSales on the class instead of an instance is trying to call it in a static context, which would be why it asks for it to be static.
Create an instance of the class and call it on that instead!
I assume that VendingMachine is the class name. You need to first create an instance of this class:
VendingMachine machine = new VendingMachine();
Then call the method on that instance:
machine.getTotalsSales()
For more details, I suggest you read a tutorial on the difference between classes and objects and how they are related.
Related
This question already has answers here:
How to Count Number of Instances of a Class
(9 answers)
Closed 4 years ago.
Suppose I have a demo.java class and have other classes like A.java , B. Java and so on.
I want to write some code in Demo.java to get the count , that will tell in how many classes Demo.java is getting called.
Any suggestions would help. Thanks in advance!
Create a static variable in class.
public static int callerCounter=0;.
And then increment it in every constructor. E.g:-
Demo()
{
callerCounter++; // Add this line in every Constructor
}
And Print callerCounter where you want to get counter value.
I do not think it is doable in general case by just analyzing the code. If the interface is in use, may not be trivial to know which class will be instantiated behind the interface. This may depend on decision within some factory and may influenced by the input that is only available at runtime, well, even by SecureRandom theoretically.
You can always put either counters or just logging statements (processing the log output separately) to collect this kind of statistics at runtime. Tools like JProfiler may work as programming-free alternative.
Create a static Set callerClasses to hold the name of each class that called your Demo class.
Then, at each call to your Demo class, add the caller name to the set.
At any point in time you can check how many different classes called your Demo class by inspecting the Set size.
EDIT NOTE #1:
The question was made clear after I posted my answer that the intention is not count for calls on methods but count instances created.
I will keep it anyway because this may be the case for someone else.
EDIT NOTE #2:
Added code sample for completeness.
public class Demo {
// ConcurrentSkipListSet for thread safety
private static Set<String> callerCount = new ConcurrentSkipListSet<>();
public void methodA() {
String className = new Exception().getStackTrace()[1].getClassName();
recordCaller(className);
}
public long getNumberOfCallers() {
return callerCount.size();
}
private void recordCaller(final String className) {
callerCount.add(className);
}
}
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 4 years ago.
public class MyResults extends Results {
...public MyResults() {
this(5);
}
public double average() {
return this.getSum()/numberOfCourses;
}
}
What do both instances of ―this mean in the code?
First instance is a call to another constructor in the same class. This is also known as Constructor Chaining pattern. Since you didn't post the entire code we don't know if that other constructor is defined (it should be, otherwise you'll have a compile time error).
Second instance is a call to the getSum() method. This method might be defined either in MyResults class or Results class (or some parent class of Results, if any).
This question already has answers here:
Does the System.out object belong to class System or class PrintStream? [closed]
(7 answers)
Closed 6 years ago.
Just started learning Java, through the "hello world" app, k learned about the object System.out.
Out is an object, but to use it, we have to write system in front of it. It's obvious and my book says that out belongs to system class.
But later in the book, my book says out also belongs to PrintStream class. That is what enable us to use println methods because they both belong to PrintStream class.
I am confused what class does out belong to?
Also, is it just a convention that for objects like out, we have to write the class as well whenever we use it. For something like;
String greeting = "Hello, World!";
If we want to use .length() method which I guess also belongs to string class, we DONT write:
int n=String.greeting.length()
Instead, it's just:
int n=greeting.();
out is a (static) member variable of class System.
It is an instance of class PrintStream.
class Foo {
String x;
}
x is a string. It is a member of class Foo. Same idea.
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 7 years ago.
I built a GUI class, and I get the pathname of the file I want to open in this GUI class. The pathname comes back as:
public String filePath = "C\blablah";
I want to actually open my file in another class, the "Network" class, so I wrote the following code to get the path string in the Network class:
String readFile = GUI.file();
Path file = Paths.get(readFile, "Network");
I tried a few different ways but it doesn't work, I thought this one would work but it comes back with
"Cannot make a static reference to the non-static method filePath()
from the type GUI"
None of those classes are my main so I cannot instantiate a GUI in the "Network" class.
Please forgive if this is a newbie question.
Edit:
This is the method I wrote in the GUI class to access the filepath in other classes
public String file(){
return filePath;
}
Ok, what you trying to do here is to access the static variable "filePath" from your GUI class, but this variable isn't static. You can change this by adding the keyword static in front of the variable name.
But I guess, that you in fact don't want to access a static variable from the class GUI, but the variable of a GUI object. In this case there's no way around but to make a GUI object with the specific path and access it from your network class.
Also note, that is a better practice to access class variables with a getter-method.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: how to call non static method from main method?
I am finding this a bit hard to implement.
I have a String[] called name which is declared globally.
String[]name;
Now i want to access this variable from the main() method. The main method is static therefore how could i access it.
I tried Animal.name but it didn't work.
How can i do this?
You need to create an instance of Animal class to access instance fields: -
Animal animal = new Animal();
animal.name; // Access array
You can solve this with two different ways, each requiring code modification:
First is to create an object of Animal type and accessing the name property.
Second is to make name as static.
like this: static String[] name = new String[10];