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

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);

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);

Strugling with the keyword this in Java

I've read a lot of explanations for the use of keyword 'this' in java but still don't completely understand it. Do i use it in this example:
private void login_BActionPerformed(java.awt.event.ActionEvent evt) {
if(user_TF.getText().equals("admin")&& pass_PF.getText().equals("admin")){
this.B.setVisible(true);
}else{
JOptionPane.showMessageDialog(null, "Warning!", "InfoBox: "+"Warning", JOptionPane.INFORMATION_MESSAGE);
}
this.user_TF.setText("");
this.pass_PF.setText("");
}
It's supposed to open a new window if a user and pass match. Do i use 'this' keyword anywhere here?
I think there are two main usages you should know:
If you have a class variable with name N, and a method variable with name N, then to distinguish them, use this.N for class variable and N for method variable. Screenshot displaying possible usage
Imagine you have 2 constructors. One takes String name, another takes name + age. Instead of duplicating code, just use this() to call another constructor. Another screenshot displaying the usage
In your case, I don't see any LOCAL (method) variables of name 'B', so I guess you can do without it.
Any non static method of the class needs an object of that class to be invoked. Class has the blueprint of the state and behavior to modify and read the state. Object is the realization of this blueprint. Once object is created , it has those states and methods.
Suppose you have below code.
public class A{
int property;
public void foo(){
bar();
}
public void bar(){
property = 40;
}
}
public class B{
public static void main(String[] args){
A obj = new A();
obj.foo();
}
}
Lets try to answer few questions.
Q1. Inside the mwthod foo we invoke bar , we have not used any explicit object to invoke it (with . dot operator), upon which object is the method bar invoked.
Q2. Method bar tries to access and modify the variable named property. Which object does this state called property belong to ?
Answers
A1. Object referred by A.this (it is same as this) . It is the object which has invoked foo method which is implicitly made available insode the called method. The object upon which execution of the method takes places can be accessed by this.
A2. same as answer to Q1.
The object at anytime can be accessed by Classname.this inside the non static methods or blocks of the class.

Calling Constructor Multiple times

How to call the Constructor multiple times using the same object
class a
{
a(int i)
{
System.out.println(i);
}
public static void main(String args[])
{
a b = new a();
int x = 10;
while( x > 0)
{
//Needed to pass the x value to constructor muliple times
}
}
}
I needed to pass the parameter to that constructor.
Constructor of a class A constructs the objects of class A.
Construction of an object happens only once, and after that you can modify the state of the object using methods (functions).
Also notice if programmer does not write any constructor in his class then the Java compiler puts the constructor for the class (public constructor without any parameters) on its own.
In the case where a constructor has been provided by the programmer, the compiler does not create a default constructor. It assumes, the programmer knows and wants creation of the objects of his/her class as per the signature of the explicit constructor.
Constructor calls are chained. Suppose there exists below class relationship.
Child.java extends Parent.java and Parent.java extends GrandParent.java.
Now if Child child = new Child(); is done, only one object is created and that is of Child.java, but the object also has all of the features of GrandParent first then with the features of the Parent and then the Child.
Hence first constructor of GrandParent.java is called then Parent.java is called and lastly the constructor of Child.java is called.
Constructors are special and different from other methods.
The intent of constructors is to create the object, so each time you use the new operator, the constructor is called and a new object is created. You can not call the constructor directly. You need the new operator to call it. Even if you see some class defining methods like getInstance(), it still uses the new operator to construct the object and return the created object.
*PS there are ways to create an object without calling constructor (like Serialization) but that is out of context of the discussion here.
Constructors are called only once at the time of the creation of the object.
Can you please be specific about what you want to achieve?
But I think you could try one of the following two things.
Calling the constructor to create a new object and assigning it to the object 'b':
b = new a(1);
Using the setter method:
void setI(int i){
this.i = i;
}
b.setI(1);
int x = 10;
while( x > 0)
{
a b = new a(x);
}

java: call static method from unknown class with polymorphy [duplicate]

This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
Closed 7 years ago.
I have superclass Token with some subclasses like Knight, King, Queen, etc.
I need a random Token Type so I call this method:
public Class randomTokenType(){
Class[] classes = {
Bishop.class, King.class, Knight.class, Pawn.class, Queen.class, Rook.class
};
Random random = new Random();
return classes[random.nextInt(6)];
}
Class<Token> tokenType = randomTokenType();
Now I want to call a static method on this tokenType, for example:
tokenType.displayString()
The compiler can't resolve this method even tough it's implemented in Token and all of its subclasses.
What is my mistake?
What you are actually looking for is reflection - see Invoking a static method using reflection
in you case that would be:
Method method = tokenType.getMethod("displayString");
method.invoke(null);
A Class-object is a sort of an index. It contains methods that allow you to query what the actual .class file contains (like its methods, fields, annotations et al).
You cannot access them directly (like an index points only to WHERE the information is - not the information itself) - instead you need to query the index with i.e. Class.getMethod("nameofMethod")
once you got the "pointer" to the method you can try to call it (via Method.invoke).
Depending on what kind of method it is, you need to pass the invoke method only null (for static methods) or an instance of the object (for non-static).
Reflection allows you to create such an instance on-the-fly as well.
For more information I suggest reading up on reflection and especially the javadoc of Class. It explains a lot.
Edit: this only works if the method displayString is declared like this:
public class Bishop{
public static void displayString() {
System.out.println("Bishop");
}
}
public class Test {
public static void main(String args[]) throws Exception {
Class<?> tokenType = Bishop.class;
Method method = tokenType.getMethod("displayString");
method.invoke(null);
}
}
if there are parameter or it is private, then this will not work
There are quite a few problems with your code. Few of them are
You are asking a class to return something.
public Class randomTokenType() //dont know what this is supposed to mean ?
If you add static to a method definition that method can never be overrriden

static/non-static method reference [duplicate]

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.

Categories