If the class Animal is nested inside Test, I get the error:
"non-static variable this cannot be referenced from a static context"
Can you please explain this error and offer a way to make this code work, while still keeping nested classes? I'd like to learn to work with nested classes and understand them better.
The error occurs when a1 is created on line: Animal a1 = new Animal();
PS: When Animal is an independent class (not nested), outside the Test class, the code DOES work, but I am interested in nesting classes.
public class Test { class Animal { String colour; void setColour(String x) { colour = x; } String getColour() { return colour; } } public static void main(String[] args) { Animal a1 = new Animal(); Animal a2 = a1; a1.setColour("blue"); a2.setColour("green"); System.out.println(a1.colour); System.out.println(a2.colour); } } Thank you in advance.