The "static context" in question here is the 'public static void main()' method. You are calling non-static method foo(int) from static method main(String), which is not allowed. Do you know why that's not allowed?
Alfonso Saenz wrote:I think is because I need an instance of Pepe class if I want to call the non-static method....
A method declared without the static keyword is called an instance method. The name of such a method tells the story: you need an instance to invoke this method. A method declared with the static keyword is a class (or static) method. And again tells the name of such a method everything you need to know: you need a class to invoke this method. So that means you can invoke a class (static) method from an instance (non-static) method (context); but you can't (directly) invoke an instance method from a class (static) method (context), as an instance is required to invoke an instance method.
And for completeness: the same rule applies to instance fields and class (static) fields as well. You can access a class (static) from an instance (non-static) context, but you can't (directly) access an instance field from a class (static) context (as an instance is required to access an instance field).
I have used the word "context", because it's more than only fields and methods. An instance (non-static) context is (obviously) instance fields and instance methods, but also constructors and instance initializer blocks. And likewise a class (static) context is (obviously) class (static) fields and class (static) methods, but also static initializer blocks.
Now let's see if you fully understand all the above. Time for a pop quiz! Which of the following lines will produce a compiler error?
Alfonso Saenz wrote:the output for foo1 is ok. That is: "in foo1 (class)".
Spot-on again! So for a class (static) method only the type of the reference variable is important. If the actual object (denoted by this reference variable) is null, it doesn't matter at all when invoking a static method, the method is still being invoked. But for an instance method, it really matters! If the reference variable is null, you'll get a NullPointerException at runtime.
Alfonso Saenz wrote:By the way: could you give me answer to my other today's question on topic: "Are static variables inherited through constructors??"