can we create an object of an interface?

Definitely, the answer is no!
But look at the code below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EmployeeSort {

	static Comparator<Employee> NAMESORT = new Comparator<Employee>(){

		public int compare(Employee e1,Employee e2){
			return e1.name.compareTo(e2.name);
		}


	};

	public static void print(List<Employee> empList){
		for (Employee o :empList){
			System.out.println(o.name);
		}
	}

	public static void main(String[] args) {
		List<Employee> empList = new ArrayList<Employee>();
		Employee e = new Employee("anil");
		Employee e1 = new Employee("babe");
		Employee e2 = new Employee("akhil");

		empList=Arrays.asList(e,e1,e2);

	    print(empList);

		Collections.sort(empList,NAMESORT);
		 print(empList);



	}

}


How do you explain the code snippet below?
 static Comparator<Employee> NAMESORT = new Comparator<Employee>(){

		public int compare(Employee e1,Employee e2){
			return e1.name.compareTo(e2.name);
		}


	};


Actually this expression instantiates a new object from an unnamed and previously undefined class, which automatically implements the interface named Comparator, and automatically extends the class named Object. The class can explicitly implement one, and only one interface, and cannot extend any class other than Object. Once again, the body of the new class is given by classBody.

I got answer from stackoverflow: http://stackoverflow.com/questions/2978849/can-anybody-explain-the-working-of-following-code?rq=1

More detailed information you can refer to the original article: http://www.developer.com/java/other/article.php/3300881/The-Essence-of-OOP-using-Java-Anonymous-Classes.htm

你可能感兴趣的:(java,interface)