Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"non-static variable this cannot be referenced from a static context"?

I'm a Java newbie and I'm trying to deploy a fibonacci trail through recursive function and then calculate the run time. here is the code I have managed to write:

class nanoTime{
    int fib(int n){
        if(n==0) return 0;
        if(n==1) return 1;
        return this.fib(n-1)+this.fib(n-2);
    }
    public static void main(String[] args){
        double beginTime,endTime,runTime;
        int n=10;
        beginTime = System.nanoTime();
        n = this.fib(n);
        endTime = System.nanoTime();
        runTime = endTime-beginTime;
        System.out.println("Run Time:" + runTime);
    }
}

The problem is when I'm trying to turn it into Byte-code I get the following error:

nanoTime.java:11: non-static variable this cannot be referenced from a static context

I'm wondering what is the problem?!

like image 394
2hamed Avatar asked Oct 03 '11 16:10

2hamed


People also ask

How do you fix non static variable this Cannot be referenced from a static context?

There is one simple way of solving the non-static variable cannot be referenced from a static context error. 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.

What does it mean by a non static variable Cannot be referenced from a static context?

And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.

Can we access non static variable in static context?

Of course, they can, but the opposite is not true, i.e. you cannot obtain a non-static member from a static context, i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs to.

How do you assign a non static variable to a static variable?

You cannot assign the result of a non-static method to a static variable. Instead, you would need to convert the getIPZip method to be a static method of your MyProps class, then you could assign its result to yor IPZip variable like this. public static String IPZip = MyProps. getIPZip("IPZip");


2 Answers

Change

n = this.fib(n);

to

n = fib(n);

and make the method fib static.

Alternatively, change

n = this.fib(n);

to

n = new nanoTime().fib(n);
like image 139
Mouscellaneous Avatar answered Sep 28 '22 07:09

Mouscellaneous


You need to instantiate a nanoTime to call an instance method, or make the fib method static as well.

like image 29
Dave Newton Avatar answered Sep 28 '22 08:09

Dave Newton