Java - Anonymous Inner Classes
In an earlier post, I said that you could not use new on abstract classes and interfaces since they were just blueprints of a class and not complete. They provide signatures for the methods, but no implementation, so of course new wouldn’t work.
However, you CAN use new on abstract classes and interfaces, but it basically requires you to provide the implementation on the spot.
Repl.it: https://repl.it/repls/UnwillingGentleOs
Let’s say you have an interface:
interface Pet {
public void greet();
}
I can call new on it by doing the following:
class Main {
public static void main(String[] args) {
Pet dog = new Pet() {
@Override
public void greet() {
System.out.println("Woof!");
}
};
Basically, I am writing a class that implements Pet on the spot and making a new instance of that, which I am calling dog.
- This allows you to skip creating a whole class in a different file if you are absolutely sure you are only going to use that particular class only once.
- Lambda expressions are only available in Java 8 and up so this is how you would do it if you did not have the ability to use Java 8 features.
Collections.sort(listOfCars, new Comparator<Car>(){
public int compare(Car c1,Car c2){
// Write your logic here.
Collections.sort(listOfCars, (c1, c2) -> {