I’ve been programming for years using .NET and I’m taking the plunge into Java with some simple starter programs.
I’m having a bit of trouble though…
When I create my start-up class with public void main, the compiler won’t let me instantiate any of the classes I’ve written?
The error I’m getting is “non-static variable _processor cannot be referenced from a static context” where _processor is the object I’m trying to instantiate from the Processor class that I wrote.
The program will compile and run just fine when I change Processor to a static class, but I don’t want to have to make all of my classes static.
Any way around this?
Thanks in advance!
Here’s everything I’ve written. It won’t compile in the current state:
class Lab
{
public static void main(String[] args)
{
Processor proc = new Processor();
proc.Go();
}
private class Processor
{
private Random _rand = new Random();
public void Processor() {}
public void Go()
{
}
}
}
Is
Processoran inner class ofLabby any chance? (yes, now that you published your code, my suspicion is confirmed).In Java, nonstatic inner classes contain an implicit reference to the containing object of the outer class, so they can’t be instantiated from static context (from your
mainmethod).So
Lab(e.g.myLab), and then callmyLab.new Processor(), orProcessorstatic (as you did), orProcessorinto a top level class.