import java.util.*;
public class testing1 {
class Inner{
String s;
Inner(String s){
this.s = s;
}
public String toString(){
return s;
}
}
public static void main(String... args)
{
List<Inner>l = new ArrayList<Inner>();
l.add(new Inner("I"));
l.add(new Inner("AM"));
for(Inner p:l){
System.out.println(p);
}
}
}
When I compile the above program,
It shows compilation error
testing1.java:16: non-static variable this cannot be referenced from a static context
l.add(new Inner("I"));
^
testing1.java:17: non-static variable this cannot be referenced from a static context
l.add(new Inner("AM"));
My problem is what does "this" refer to in the above two lines ?
But when I modify my program as ->
import java.util.*;
public class testing1 {
int x;
class Inner{
String s;
Inner(String s){
this.s = s;
}
public String toString(){
return s;
}
}
public static void main(String... args)
{
List<Inner>l = new ArrayList<Inner>();
l.add(new testing1().new Inner("I"));
l.add(new testing1().new Inner("AM"));
for(Inner p:l){
}
}
}
It compiles . Why?
Can anyone help me.