Method Calls Not Working [duplicate] - java

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
The method calls at the end of the main method are giving me an error saying "non-static method cannot be referenced from a static context" I'm not sure what I'm doing wrong in the method call.
public static void main(String[] args)
{
ArrayList<Candidate> voteCount = new ArrayList<Candidate>();
//add objects to voteCount
printListResults(voteCount);
totalListVotes(voteCount);
printListTable(voteCount);
}
public void printListResults(ArrayList<Candidate> election)
{
//some code
}
public int totalListVotes(ArrayList<Candidate> election)
{
//some code
}
public void printListTable(ArrayList<Candidate> election)
{
//some code
}

You simply need to declare these methods as static
public static void printListResults(ArrayList<Candidate> election) {
//some code
}
public static int totalListVotes(ArrayList<Candidate> election) {
//some code
}
public static void printListTable(ArrayList<Candidate> election) {
//some code
}
An alternative approach would be to instantiate an object of your class, as pointed out in the answer from JoschJava. Either way will work. Which approach you choose is partly a matter of taste and partly depends upon the needs of your application (which is beyond the scope of this question).

The problem is that you're trying to call a class method from a static method. You need to instantiate your class:
YourClass classObj = new YourClass();
classObj.printListResults(voteCount);

Related

How to access static block variables outside of class in java [duplicate]

This question already has answers here:
What is the scope of variables declared inside a static block in java?
(4 answers)
Closed 3 years ago.
I was working on some code in which I need to access the variable "hs" present in the static block of one class from another.
Note: Both the class are preset in different packages.
Code is as follow:
public class A{
static {
HashSet<String> hs = new HashSet<>();
}
}
I Googled about it but nothing found anything helpful.
Your help would be very appreciable.
EDIT: I am not allowed to make changes in this file still need to access it from the other file.
Why I need to do this cause I am doing unit testing by JUnit and there is nothing what this block is returning which I can put assertEquals() on. So the option I left with is to test the side-effects and this variable "hs" value is getting changed as a side-effect. That's why I need to access it from another file.
Declare it as public static inside the class and initialize it in static block
class A1{
public static HashSet<String> hs;
static {
hs= new HashSet<>();
}
}
Need create getter and setter for variable "hs".
Class 1:
public class Test {
public static HashSet<String> hs;
static {
hs = new HashSet<>();
hs.add("Test14");
hs.add("Test15");
hs.add("Test16");
}
public static HashSet<String> getHs() {
return hs;
}
public static void setHs(HashSet<String> hs) {
Test.hs = hs;
}
}
Class 2
If you need to use "hs" variable in without static method then:
public class Test2 {
public void test() {
Test ts = new Test();
ts.getHs();
}
}
If you need to use "hs" variable in with static method then:
public class Test2 {
public static void test() {
Test.getHs();
}
}

Scope of statics and key word "this" in java [duplicate]

This question already has answers here:
Why can't we use 'this' keyword in a static method
(9 answers)
Closed 5 years ago.
I have a question about this fragment of code :
public class Inner {
static int a;
public static void main(String[] args) {
a = 0;
}
public static void g() {
this.a = 0;
}
}
`
Why we can't use "this.a" in static method, but we can use "a" without "this"?
Photo of compilation error: https://www.dropbox.com/s/5q6y3ldsf37p0h3/%D0%97%D0%BD%D1%96%D0%BC%D0%BE%D0%BA%20%D0%B5%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202017-05-27%2017.28.34.png?dl=0
Because this points to an instance of the class, in the static method you don't have an instance.
The this keyword refers to the current instance of the class. Static member functions do not have a this pointer
You'll notice the definition of a static member is
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object
Which is why this has nothing to point to.

Does static variable inherited? [duplicate]

This question already has answers here:
Are static variables inherited
(4 answers)
Closed 4 years ago.
We know that in java static variable are not inherited. But in below code I am not getting any error as I want to initialize the static variable in child class.
class s
{
static int x;
}
class aaa extends s
{
void fun()
{
x=2;
System.out.println(x);
}
public static void main(String args[])
{
aaa w=new aaa();
w.fun();
}
}
static members are most definitely accessible from subclasses, as your example shows. You cannot override them, of course, but you could hide them.

a function is required to be static in java [duplicate]

This question already has answers here:
cannot make a static reference to a non static method
(5 answers)
Closed 7 years ago.
The following block has an error. It requires the createArrayList function to be static. I cannot understand the reason. I appreciate if anyone can explains that to me in an understandable way.
import java.util.ArrayList;
public class Ceasefire {
public static void main(String[] args)
{
createArrayList();
System.exit(0);
}
public void createArrayList()
{
ArrayList<String> aL1 = new ArrayList<String>();
aL1.add("Item1");
aL1.add("Item2");
aL1.add("Item3");
System.out.println(aL1);
}
}
You cannot call a non-static (createArrayList) method from a static one (main). A static method can only call other static methods, but no instance methods.

Get Class Type from Reflection Java [duplicate]

This question already has answers here:
How do I find the caller of a method using stacktrace or reflection?
(13 answers)
Closed 7 years ago.
When I call on a method in a class, the method will get the java.lang.Class that called on it using sun.reflect.Reflection.getCallerClass(2). This is not what I want. I want the Reflection to return the class Object that called on it (i.e. if I call the method from the Bar class, the Reflection.getCallerClass() returns an object of type Bar)
Let's suppose I have this class:
public class Foo {
public static void printOutCallerObject() {
System.out.println(classTypeThatCalledOnMethod);
}
}
Called by:
public class Bar {
public static void main(String[] args) {
Foo.printOutCallerObject();
}
}
And then the program would print out "Bar".
Here's a quick demo of how you can get the calling class - you cannot get the calling object unless you pass it to the method because it is not on the stack.
public class ReflectDemo {
public static class Foo {
public static void printOutCallerObject() {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
// trace[0] is Thread.getStackTrace()
// trace[1] is Foo.printOutCallerObject()
// trace[2] is the caller of printOutCallerObject()
System.out.println(trace[2].getClassName());
}
}
public static class Bar {
public static void barMain() {
Foo.printOutCallerObject();
}
}
public static void main(String[] args) {
Foo.printOutCallerObject();
Bar.barMain();
}
}
This prints:
ReflectDemo
ReflectDemo$Bar
And Foo.printOutCallerObject(); will print out the class of whatever code calls it. The call to Thread.currentThread().getStackTrace() isn't cheap, so be aware that you may incur some runtime costs. This pattern is often used for logging, to record which piece of code triggered the logging call.

Categories