Cannot make static reference to non static method in java

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

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.

4 Answers 4

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

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.

You could create an instance of the class you want to call the method on,

new lookFor().USER(target, list); 

Linked

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Cannot make a static reference to the non-static method

Building a multi-language application in Java. Getting an error when inserting String value from R.string resource XML file:

public static final String TTT = (String) getText(R.string.TTT); 

Never store string resources in static data members. Always request them via getString() when you need them. That way, your application properly adjusts to users changing their chosen language.

8 Answers 8

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass(); 

To call an instance method, you call it on the instance ( myObject ):

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test < string somedata = "99"; string getText() < return somedata; >static string TTT = "0"; > 

Now I have the following use case:

Test item1 = new Test(); item1.somedata = "200"; Test item2 = new Test(); Test.TTT = "1"; 
in item1 TTT = 1 and somedata = 200 in item2 TTT = 1 and somedata = 99 

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test < string somedata = "99"; string getText() < return somedata; >static string TTT = getText(); // error there is is no somedata at this point > 

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

it static because i call it from several files in my project. when i removed the "static" the error code is gone, but now i have lots of errors in other files that using this variable.

when i add the line "Constants notifications_values = new Constants(); to my main activity class, it compile OK but in the emulator it crash when this activity run

There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String .

A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.

And to call this from your Activity :

This will allow you to access your String resource without needing to use a public static field.

Источник

how to solve "cannot make a static reference to the non-static method"? [duplicate]

i have problem with the "getClass", the eclipse writing this messeage: "cannot make a static reference to the non-static method getClass() from the type Object" this is the code:

 public static void main(String[] args) < JFrame f = new JFrame(); File path = new File(getClass().getResource("/resources/image.jpg").getFile()); BufferedImage image = ImageIO.read(path); 

You are using getClass() - which is a public non-static method in the class that main is in. If you want to get getClass() - you need to first create an instance of this class, and call it on it.

@leonardkraemer: The dupe doesn't answer this specific problem an doesn't equip anyone to be able to answer it, unfortunately.

@Makoto it should be stackoverflow.com/questions/8275499/… nevertheless it is 2 seconds of googling. I cant raise the flag again for the new dupe :/ Nevertheless the linked dupe educates about the reason for the error, which should help in the long run.

@leonardkraemer: Hopefully then you'll be suggesting better duplicates in the future with a bit more time to Google for them? 🙂

3 Answers 3

(If your class name is Main then) use Main.class.getResource instead of this.getClass.getResource

A static method belongs to the class .

A non-static method belongs to an instance of the class.

when you call getResource() , it isn't associated with any instance.

Main.class.getResource("images/pic.png") 

you can find more information about static at here

The static key word means the function "main" in this case is bound to the class itself, therefore you cannot call a method that is not static like this " getClass() " because then that would be the same as saying " this.getClass() " but this can't refer to any object since you are calling getClass in a static method. Hence why you have to reference the class itself inside the static method saying MainClass.class.getResource()

Источник

Cannot make a static reference to the non-static method

I have searched for this problem and found many answers regarding it but however i did not understand them , i would a clarification regarding my own code so hopefully it will makes sense i am trying to call the PrintList method in the main method but i get this error Cannot make a static reference to the non-static method PrintList() from the type Stack if i change the modifier of PrintList to static , it ruins the whole code. can anyone help me fix this issue please? Thanks

public class Stack  < public int N; // size of the stack public Nodefirst; // top of stack public Node last; // top of stack // helper linked list class private static class Node  < private Item item; private Nodenext; > public Stack() < first = null; last = null; N = 0; >public void PrintList() < Nodecurrent; current = first; while (current.next != null) < System.out.println(current.item); current = current.next; >> public static void main(String[] args) < // Declare the stack Stacks = new Stack(); s.push("Bob"); s.push("Mary"); s.push("David"); s.InsertBegin("George"); System.out.println("First item: " + s.peek()); Object current; PrintList(); // what is wrong here? > > 

@KickButtowski - it's the very last line (not counting the closing braces) where he/she calls PrintList() .

Object current doesn't do anything? In JAVA it's convention to name methodes like this: printList() so with a starting lowercase.

Next time when you ask a question, try to reduce the problem. Minimize the amount of code and if you still have the same error post that minimum amount of code, instead of pages of code.

3 Answers 3

The problem is that you are not specifying the instance that PrintList is to be called on. To fix that, change this:

 PrintList(); // what is wrong here? 

What you really need is to understand exactly what static and non-static actually mean.

First, some background. Apologies if some of this is already familiar to you. Java is an object oriented language, you create a class to act as a template for a specific type of object, defining what attributes (variables) that it has, and how it behaves (methods). These attributes and behaviours belong to objects of that class:

public class Person < private String forename; private String surname; public Person(String forename, String surname) < this.forename = forename; this.surname = surname; >public String getFullName() < return forename + " " + surname; >public static void main(String[] args) < Person john = new Person("John", "Doe"); >> 

The above code defines a template for creating objects of the type Person , each having a forename and a surname , both of the type String . It also defines a behaviour that allows you to get a Person 's full name using the getFullName() method.

Both forename and surname , as well as getFullName() are examples of non-static fields/methods. That is, they belong to a specific Person object. Importantly: none of these can exist without a Person object being created first. In this case we have a Person object called john which has a forename of "John" and a surname of "Doe". If we were to call john 's getFullName() method:

Then we'd get "John Doe" back.

The opposite of this is static . Static things do not belong to an object, instead, they belong to a class .

public class Person < private String forename; private String surname; private static String species = "Homo sapiens"; public Person(String forename, String surname) < this.forename = forename; this.surname = surname; >public String getFullName() < return forename + " " + surname; >public static void main(String[] args) < Person john = new Person("John", "Doe"); >> 

Here the String species doesn't belong to john , it belongs to Person . Static methods and variables don't need an object in order to exist, they always* exist. You access it by using the class itself as a reference, like this:

In your example, you have defined a method PrintList() as a behaviour of objects of the Stack class. The problem is that you're inside the main method, which is static . This means that you aren't in the 'context' of an object (because main belongs to Stack , not objects of the type Stack ) when you're trying to call the PrintList() method. When you're inside a static method, in order to call a non-static method or access a non-static attribute, you must do so using a reference to an object of the class that owns it. In your case, you already have this reference in the form of s , so you can call your PrintList() method like so:

NB: Conventionally in Java we use camelCase for method names, so it really should be printList() .

When I first started to learn Java, I found the concept of static very difficult to wrap my head around - because I hadn't learned to think in an object-oriented way yet. When the penny drops, you'll wonder why you ever struggled with it. Hopefully this will help you get closer towards that penny-drop moment!

*As long as the class is loaded and it's not a compile-time constant (but you don't need to worry about those yet).

Источник

Java Error: Cannot make a static reference to the non-static method

I'm writing an Android app and am getting this error, but I'm not sure why. Can someone help me understand why I'm getting this error?

Cannot make a static reference to the non-static method updateScores(List) from the type DatabaseHandler 
public class ScoreList extends SherlockFragmentActivity < ListlistScore = new ArrayList(); public void updateListView() < listViewScore.setAdapter(new ScoreListAdapter(ctx, R.layout.score_row_item, listScore)); DatabaseHandler.updateScores(listScore); >> 

Here's the DatabaseHandler class. I tried making the function static, but it won't work that way due to errors.

public class DatabaseHandler extends SQLiteOpenHelper < private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "scoreKeeper"; private static final String TABLE_GAMES = "games"; private static final String KEY_NAME = "name"; private static final String KEY_CHANGE = "scoreChange"; private static final String KEY_TOTAL = "scoreTotal"; public DatabaseHandler(Context context) < super(context, DATABASE_NAME, null, DATABASE_VERSION); >@Override public void onCreate(SQLiteDatabase db) < String CREATE_GAMES_TABLE = "CREATE TABLE " + TABLE_GAMES + "(" + KEY_NAME + " INTEGER PRIMARY KEY," + KEY_CHANGE + " TEXT," + KEY_TOTAL + " TEXT" + ")"; db.execSQL(CREATE_GAMES_TABLE); >@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) < db.execSQL("DROP TABLE IF EXISTS " + TABLE_GAMES); onCreate(db); >public void addScore(Score score) < SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, score.getName()); values.put(KEY_CHANGE, score.getScoreChange()); values.put(KEY_TOTAL, score.getScoreTotal()); // Inserting Row db.insert(TABLE_GAMES, null, values); db.close(); >public List getAllScores() < ListscoreList = new ArrayList(); String selectQuery = "SELECT * FROM " + TABLE_GAMES; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) < do < Score score = new Score("","",""); score.setName(cursor.getString(0)); score.setScoreChange(cursor.getString(1)); score.setScoreTotal(cursor.getString(2)); // Adding contact to list scoreList.add(score); >while (cursor.moveToNext()); > return scoreList; > public void updateScores(List score) < SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DROP TABLE IF EXISTS " + TABLE_GAMES); onCreate(db); ContentValues values = new ContentValues(); for(int i = 0; i < score.size(); i++)< values.put(KEY_NAME, score.get(i).getName()); values.put(KEY_CHANGE, score.get(i).getScoreChange()); values.put(KEY_TOTAL, score.get(i).getScoreTotal()); >> > 

Источник

Читайте также:  Developer Helps | Display None
Оцените статью