Before I start, I would like to point out that this post is not a duplicate of:
How to instantiate non static inner class within a static method
or
Why instantiation of static nested class object is allowed?
In fact I would like to hear why it behaving strangely in my sample code. As of my understanding, we can instantiate a static inner class something like this:
new OuterClass.InnerClass();
But in my sample code, I'm able to instantiate static inner class something like:
new InnerClass();
I will put my sample code here:
import java.util.*;
class GFG {
static class ListComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2){
if(o1>o2){
return -1;
}
else if(o1<o2){
return 1;
}
else
return 0;
}
}
public static void main (String[] args) {
//code
List<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(1);
list.add(2);
list.add(4);
Collections.sort(list,new ListComparator());
for(Integer i : list){
System.out.println(i);
}
}
}
The above code run without any error and I get output in descending order. Can anyone explain how I am able to directly instantiate a static inner class like this: new ListComparator();
I was expecting error in this case, but surprised by the output. I know my static inner class implementing Comparator interface, but I was wondering making it static would raise a conflict with the behavior of static class. But surprisingly did not happen and I'm curious why it didnt happen?