Error non static method java

The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message: You can ei...

I think it is worth pointing out that by the rules of the Java language the Java compiler inserts the equivalent of «this.» when it notices that you’re accessing instance methods or instance fields without an explicit instance. Of course, the compiler knows that it can only do this from within an instance method, which has a «this» variable, as static methods don’t.

Which means that when you’re in an instance method the following are equivalent:

instanceMethod();
this.instanceMethod();

and these are also equivalent:

... = instanceField;
... = this.instanceField;

The compiler is effectively inserting the «this.» when you don’t supply a specific instance.

This (pun intended) bit of «magic help» by the compiler can confuse novices: it means that instance calls and static calls sometimes appear to have the same syntax while in reality are calls of different types and underlying mechanisms.

The instance method call is sometimes referred to as a method invocation or dispatch because of the behaviors of virtual methods supporting polymorphism; dispatching behavior happens regardless of whether you wrote an explicit object instance to use or the compiler inserted a «this.».

The static method call mechanism is simpler, like a function call in a non-OOP language.

Personally, I think the error message is misleading, it could read «non-static method cannot be referenced from a static context without specifying an explicit object instance«.


What the compiler is complaining about is that it cannot simply insert the standard «this.» as it does within instance methods, because this code is within a static method; however, maybe the author merely forgot to supply the instance of interest for this invocation — say, an instance possibly supplied to the static method as parameter, or created within this static method.

In short, you most certainly can call instance methods from within a static method, you just need to have and specify an explicit instance object for the invocation.

Many programmers face the error message ‘Non static method cannot be referenced from a static context’ when they are coding. This error message isn’t specific and can occur in any IDE if the conditions for the error are true.

Non Static Method Cannot be Referenced from a Static Context

This is a very common mistake for beginners where the programmer tries to use a class ‘statically’ without making an instance of the class. There are several conditions which must be met when you are using a class which is static. In this article, we will go through several different cases and guide you on how to use a static class.

What is a Static Method?

Adding the keyword ‘static’ to any method makes the method known as a static method. A static method belongs to the class rather than belonging to an object (which is the norm). A static method can be easily invoked without the condition of creating an instance of a class.

There are several different uses of Static methods for example, using it, you can change a static data member and its value. However, there are still some limitations when using a Static method. For example, if you want to access non-static fields of your class, you must use a non-static method. So to sum up, Static methods are used very sparely but they do have their benefits.

Here is a short example of how a static method can be made to change the property of all objects.

class Students{ 

 int roll_no; 

 String name; 

 static String college = "InformationTech"; 

 static void change(){ 

 college = “Management"; } 

 Students (int number, String name_self){ 

 roll_no = number; 

 name = name_self;  } 

 void display (){System.out.println(rollno+" "+name+" "+college);} 

public static void main(String args[]){ 

Students.change(); 

Students stu_1 = new Students (100,"Mexican"); 

Students stu_2 = new Students (202,"American"); 

Students stu_3 = new Students (309,"British"); 

stu_1.display(); 

stu_2.display(); 

stu_3.display(); 

}  }

The output of the program will be:

100 Mexican Management 202 American Management 309 British Management

What is the Difference between a class and instance of a class?

Think you are walking on the street and you see a car. Now you immediately know that this is a car even if you don’t know what is its model or type. This is because you know that this belongs to the class of ‘cars’ which you already know of. Think of class here as a template or an idea.

Now as you move closer, you see the model and make of the car. Here you are recognizing the ‘instance’ of the class ‘car’. Here all the properties will be present in detail; the wheels, the horsepower, the rims etc.

An example of properties can be that the class ‘car’ states that all cars should have wheels. The car which you are seeing (an instance of the car class) has alloy rims.

In object-oriented programming, you define the class yourself and inside the class, you define a field of the type ‘color’. Whenever the class is instantiated, memory is automatically reserved for the color at the backend and later on, you can give this a specific value (for example red). Since attributes like these are specific, they are non-static.

In contrast, static methods and fields are shared with all the instances. These are made for value or items which are specific to the class and not the instance itself. For methods, there can be global methods (for example, stringtoInt converter) and for fields, they are usually constants according to your code (for example, the car type can be static if you are only manufacturing normal cars).

Now, we will look at all the different cases where your coding can go wrong and see the workarounds to fix them.

Issue 1: You are calling something which doesn’t exist

We came across some cases where users were using both static and non-static methods with each other. When we do this, you should be careful of what method is calling what (in terms of static or not). Take a look at the following code:

private java.util.List<String> someMethod(){

    /* Some Code */

    return someList;           }

public static void main(String[] strArgs){         

     // The following statement causes the error. You know why..

    java.util.List<String> someList = someMethod();        }

Here, the static method is calling someMethod. In object-oriented programming, we encapsulate the data together with the data which we want to operate on. Here, without an object, there is no instance data and while the instance methods exist as part of the class definition, there should always be an object instance to provide data to them.

So to sum up, you cannot call something which doesn’t exist. Since you might not have created an object, the non-static method doesn’t exist yet. However, on the other hand, a static method will always exist (because of definition).

Issue 2: Methods aren’t made Static

If you are invoking methods from your Static main method without creating an instance of the methods, you will get an error message. Here, the same principle applies; you cannot access something that doesn’t exist.

public class BookStoreApp2 {

    //constants for options

    Scanner input = new Scanner (System.in);

    public static void main(String[] args) {

        BookStoreItem[] item;//declaring array

        item = new BookStoreItem[10];//initializing array

        int itemType = -1;

        printMenu();

        getUserChoice();

        for (int i = 0; i < item.length; i++){

            }//end of switch statement

        }//end of for loop

        for (int i = 0; i < item.length; i++) {

        }//end of for

    }//end of main method

Here in this code, you need to convert both the methods printMenu() and getUserChoice() into static methods.

Hence if you want to get around a situation like this, you can use a constructor instead. For example, you can take the contents of your main() method and place them inside a constructor.

public BookStoreApp2()

{
   // Put contents of main method here}
After doing this, do the following inside your main() method:

public void main( String[] args )

{ 
new BookStoreApp2();           }

If these tips don’t work on your or your code is different, you should keep in mind the basic principles of Static classes and methods and recheck your code to make sure that the basic principle is not being violated.

The error non static variable cannot be referenced from a static context in Java is mostly faced by the beginners at the time of compilation of Java program. The reason to occur this error is that they use a non-static member variable in the main() method. Because the main() method in Java is a static method and it is invoked automatically, we need not to create an object to invoke it. To understand the error, first we should understand the static and non-static method in Java.

Static Method

In Java, public methods belong to an instance of class but if we talk about static method, they belong to a class not to an instance of a class. There is no need of creating an instance of the class to invoke a static method. The static member can access only the static data member and can change its value.

Non-static Method

All the methods without having static keyword before method name are referred to as Non-static methods. There is no need to create an instance of the class for accessing the static method and static variable. The non-static methods are used dynamic or runtime binding. Unlike static method, we can override the non-static method.

Let’s create a Java program and generate the same error.

In the following example, we have declared a private variable number of type int before the main() method. In the main() method, we are trying to increment the number by 1. It is to be noted that the main() method is a static method and the variable is not static. When we compile the above program, we get the same error, as we have shown below.

StaticExample1.java

Output:

Why non-static variable cannot be referenced from a static context in Java

Now, let’s declare the variable number as static and compile the code. Note that, variable and the main() method both are static.

StaticExample2.java

Output:

Why non-static variable cannot be referenced from a static context in Java

The program compiles and run successfully.

Each instance of a non-static variable has a different value and is created when the new() operator initializes an instance of an object. The static variables are created or initialized when the class loads into JVM.

We need an instance of an object for calling the non-static variable. We can create many objects by giving different values to that non-static or instance variable.

StaticExample3.java

Output:

Why non-static variable cannot be referenced from a static context in Java

In the above program, three objects, var1, var2, var3, are created for the class variable and assigned the three different values 12, 13, 14 for the objects var1, var2, and var3, respectively. Now, the number property of each object has its own integer value. When we try to increment the value of the number property by calling the increment() method, the compiler doesn’t understand for what value of number the method should increment the value. The compiler faces the ambiguity error and throws the compile-time error non static variable cannot be referenced from a static context.

Solution to The Error

There is one simple way of solving the non-static variable cannot be referenced from a static context error. In the above code, we have to address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context. A new copy of all the non-static variables is created when a new instance of variable is created. So, we can access these variables by using the reference of the new instance of the class. for example, consider the following Java program.

StaticExample4.java

Output:

Why non-static variable cannot be referenced from a static context in Java

Description

In the above program, we access the number property by using the class name staticExample. We create an object of the StaticExample class name test and increment the number’s value by using the test object.


Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let’s discuss why non-static variable cannot be referenced from a static method. 
Before getting into the error, lets first understand what each of the methods means: 
 

  • Static Method: A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
  • Non-static method: Any method whose definition doesn’t contain the static keyword is a non-static method. In the non-static method, the method can access static data members and static methods as well as non-static members and method of another class or same class, also can change the values of any static data member.

What is the Issue with non-static variable referenced from static context?
Let’s consider the following code where class A is created with a non-static variable and a static method. The object of this class is being created in another class and the static method is being accessed as follows:
 

JAVA

class A {

    int N;

    public static void increment()

    {

        N++;

    }

}

public class Demo {

    public static void main(String args[])

    {

        A obj1 = new A();

        A obj2 = new A();

        A obj3 = new A();

        obj1.N = 3;

        obj2.N = 4;

        obj3.N = 5;

        A.increment();

        System.out.println(obj1.N);

        System.out.println(obj2.N);

        System.out.println(obj3.N);

    }

}

IF this code could actually be run, you would expect the output to be: 
 

4
5
6

But instead a compile-time error is thrown
 

Compile Errors:

prog.java:16: error: non-static variable N cannot be referenced from a static context
        N++;
        ^
1 error

As we can see that the above program gives the error. Though in the above code, all the objects names have the same variable name N, if we try to increment N, its giving an error. This error is very common during object oriented programming. 
Why does this error occur?
For the non-static variable, there is a need for an object instance to call the variables. We can also create multiple objects by assigning different values for that non-static variable. So, different objects may have different values for the same variable. In the above program we have created three objects obj1, obj2, obj3 for the class A and assigned the three different values 3, 4, 5 for the objects obj1, obj2, obj3 respectively. When we try to call the function increment, as every object of N have its own value there will be ambiguity for the compiler to understand for what value of N should the method increment the value.
How to solve this error? 
In order to avoid ambiguity, the java compiler throws a compile time error. Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created. By using the reference of the new instance, these variables can be accessed. For example:
 

Java

public class GFG {

    int count = 0;

    public static void main(String args[])

    {

        GFG test = new GFG();

        test.count++;

        System.out.println(test.count);

    }

}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error 1415 sql
  • Error node interpreter path is incorrect please check interpreter settings
  • Error nod3ddevice что это
  • Error nod3ddevice как исправить
  • Error no wgl extensions

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии