static/non-static method reference [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)
Closed 7 years ago.
I started creating a Hangman game. I want to have a main class, and a method class. I want to get a secret word, but I get an error:
non-static method getWord() cannot be referenced from a static context.
Maybe I get this error because no object has been created? What's wrong here and how do I fix this?
PS: maybe implementing it with enum could be better, but I want to start this way.
public class HangmanMain {
public static void main(String[] args) {
String secretWord; /* chosen secret word*/
secretWord = HangmanUtil.getWord();
System.out.println("");
}
}
public class HangmanUtil {
private String[] wordBank = {"pool","ice", "america", "hook", "book", "glass" , "hint", "giraffe"," elephant", "ocean","market"};
String guess;
private int bodyPartsLeft;
String getWord(){
int len = wordBank.length;
int rand = (int)(Math.random() * (len + 1));
return wordBank[rand];
}
}

You answered yourself :
Maybe I get this error because no object has been created ?
Either create a new instance of HangmanUtil or make the HangmanUtil.getWord() method static.
EDIT : considering it's a utility class, I believe second option is better : make HangmanUtil a static class with static methods.

You can't call a method via ClassName.methodName() unless the method is static.
If you want to call a non-static method, you need an instance. E.g.
HangmanUtil hu = new HangmanUtil();
secretWord = hu.getWord();
If you don't want to make an instance, then your method needs to be be marked static, and any other methods or fields it references must also be static.

Related

What is the proper way of calling a function of a same class without using objects in java? [duplicate]

This question already has answers here:
"Non-static method cannot be referenced from a static context" error
(4 answers)
Closed 3 years ago.
How do I call a function of the same class in java without using an object?
I tried this but got an error:
'non-static method facti(int) cannot be referenced from a static context'
System.out.print(facti(number));
public class Facto {
int i, fact =1;
int facti(int num){
if(num == 0){
System.out.print("For Zero ");
return 1;
}
else
for (i = 1; i <= num; ++i)
{
fact = fact * i;
}
return fact;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number for factorial : ");
int number = sc.nextInt();
Facto f1 = new Facto();
System.out.println(f1.facti(number));
}
}
Simple answer: you can't.
Your main method is 'static' it only can call other static methods (in the same class) or methods of an object. So you either can make "facti" static, too. Or you create an object: Facto f = new Facto(); f.facti(13); and call facti on that object.
Methods in Java are bound to objects unless specified otherwise. For example, consider the function foo(String str) in the class Bar:
public class Bar {
public void foo(String str) {
doSomething(this);
System.out.println(str);
}
}
This method is "attached" to a particular instance of the class Bar, meaning that it is effectively passed in as another parameter (e.g. like foo(String str, Bar this)). In Java, this is a reserved keyword, and refers tho this "hidden parameter".
Since this method has this hidden parameter, you must call it on an instance of Bar, for example:
Bar bar = new Bar();
bar.foo("hello");
If you just call: Bar.foo(), the "hidden parameter" does not know what it should be, and so this fails at compile time.
If, however, you do not need to refer to a particular instance during your method, you can mark it as static. This means you can call it on a class, rather than a type, like Bar.foo();
The error you are receiveing (non static method cannot be refernenced from a static context) is saying:
you are trying to call a non-static method facti(int i) (or, with a "hidden parameter", facti(int i, Facto facto)).
The context (i.e. the method you called it from: public static void main(String[] args)) is a static method, and so does not have this hidden parameter.
To fix it, either:
Make your method static, to avoid the need for a particular instance of Facto
Create an instance using new Facto(), and call it on that: e.g. new Facto().facti(123);

When Should You Use Get Methods vs Call Variables Directly? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 4 years ago.
ok so i just found out that if you have a class with global variables you can call it in another class just by saying class.variable and now i'm very confused as to why getVariable and setVariable methods exist ever when they're already accessible
so let's say we have these two classes
public class MyClass {
public int num;
public String str;
public MyClass (int num, String str) {
this.num = num;
this.str = str;
}
public int getNum () {
return num;
}
public String getStr () {
return str;
}
}
public class test {
public static void main (String[] args) {
MyClass x = new MyClass (3, "string");
System.out.println(x.num);
System.out.println(x.str);
System.out.println(x.getNum());
System.out.println(x.getStr());
x.num = 4;
System.out.println(x.num);
}
}
Both ways, it accesses the same data from the object and outputs the same thing. Is one way better practice than the other or are there certain cases where one of the ways won't work?
Short answer: encapsulation.
A major benefit is to prevent other classes or modules, especially ones you don't write, from abusing the fields of the class you created.
Say for example you can an instance variable int which gets used as the denominator in one of your class methods. You know when you write your code to never assign this variable a value of 0, and you might even do some checking in the constructor. The problem is that some else might instantiate your class and later assign the instance variable a value of 0, thereby throwing an exception when they later invoke the method that uses this variable as a denominator (you cannot divide by 0).
Using a setter, you write code that guarantees the value of this variable will never be 0.
Another advantage is if you want to make instance variables read only after instantiating the class then you can make the variables private and define only getter methods and no setters.

Instance variable value not being printed [duplicate]

This question already has answers here:
non static variable name cannot be referenced from a static context [duplicate]
(5 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
I am trying to learn java. currently learning about types of variables.
i have written a small program defining instance,local,static variables and trying to print the same from with in the main method. but i am getting error saying "non static variable i cannot be referenced from static context. Below is my program
public class variable{
int i=5;
static int j=10;
public static void main(String[] args){
int k=15;
System.out.println(i);
System.out.println(j);
System.out.println(k);
}
}
Please let me know whats wrong with the program
You need to create a instance of variable and access i
variable v = new variable();
// then access v.i
BTW use Camelcase for you class name.
int i should be static becasue static context cant refer to the non-static variable
Options:
Make a new instance of your class so you can reach i. In fact it is maybe not the best option, because you should make it private, and add a getter method... :)
OR
You could change int i to static int i, because of the static main method.
+1 : it is better to have classnames camescased... :)

JAVA - Cannot make a static reference to the non-static method [duplicate]

This question already has answers here:
Java Error: Cannot make a static reference to the non-static method
(7 answers)
Closed 7 years ago.
public class lookFor {
//Tools
//It returns the position of an element at the ArrayList, if not found returns -1
public int User(String target, ArrayList<User> users){
for(int i = 0; i < users.size(); i++){
if(users.get(i).getUserName().equals(target)){
return i;
}
}
return -1;
}
}
For some reason, when i try to call "User" This Error appears
And asks me to make the "user" method a static method, but i don't know what repercussion will it have.
A static method belongs to the class, a non-static method belongs to an instance of the class.
You need to create an instance of the class:
lookFor look = new lookFor();
And write like this:
if(look.User(username,users)==-1){....};
Static means there is one for an entire class, whereas if it is non-static there is one for each instance of a class (object). In order to reference a non-static method you need to first create an object, and call it.
In order to use the User method in a static context (main method for the example), you need to instantiate the lookFor class and call the User method on that object :
lookFor look = new lookFor(); // Use appropriate constructor
if(look.User(username, users) == -1) {
...
}
You have to make an instance of the lookFor class in order to call it's non-static methods.
lookFor lf = new lookFor();
if(lf.User(username,users)==-1) {
...
If you are trying to access USER method within static method then you get this error.
The only way to call a non-static method from a static method is to
have an instance of the class containing the non-static method. By
definition, a non-static method is one that is called ON an instance
of some class, whereas a static method belongs to the class itself.
For example :
You could create an instance of the class you want to call the method on,
new lookFor().USER(target, list);

Why should my method be static? [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
Hi I have this piece of code and i am really confused to why i have to make the lel method static.The error is this "non static method cant be referred from static content". Usually when I create methods either to construct new objects or to manipulate objects in the main method I do not get this error message.Plus, i never declared e to be static!!. can someone please explain to me why this occurring?? Thank you :)
class x {
public static void main(String[]args){
int e= 2232;
e= lel(e);
}
int lel(int k){
return k+1;
}
}
There are two solutions you could implement. The first option is to make your int lel(int k) a static method which would look like static int lel(int k)
Your other option is to declare a new object of your class x and use that for your lel method within main as MickMnemonic suggested in the comments. That code would look like:
e = new x().lel(e);
I believe the simplest thing would be to make the lel method static but it is up to you.
A deeper explanation of static methods can be found here.

Categories