Java Interface Anonymous.

Java Interface and anonymous inner class

  • Anonymous inner class is a class that has no name and the implementation is combined with instantiation of an object.
  • Can also be created through extending a class, but in this case as implementing an interface.
    Using an interface implementation example:
    interface Reputation {
      // default method
      default public String getInfo() {
        return "Bad for business";
    class Car {
      private String initialReputation=null;
      private List<String> reputations= new ArrayList<String>();
      public Car() {
      public Car(String initialReputation) {
      public void addReputation(String reputation) {
      Reputation obj = new Reputation() {   // Anonymous inner class
        @Override       // Overriding interface default method
        public String getInfo() {
          String returns ="";
          if (initialReputation==null){
            returns = Reputation.super.getInfo();
          }else {
           returns = initialReputation; 
          for (String ret : reputations) {
            returns +="\n"+ret;
          return returns;
    public class CarReputationApp {
      public static void main(String[] args) {
        Car myCar1 = new Car("High performance"); // instantiated object of class car
        myCar1.addReputation("New car");
        myCar1.addReputation("Comfortable to drive");
        myCar1.addReputation("Low price");
        System.out.println("Car 1 reputations:\n" + myCar1.obj.getInfo());
        Car myCar2 = new Car();
        System.out.println("\nCar 2 reputations:\n" + myCar2.obj.getInfo());
    The result of this is:
    Car 1 reputations:
    High performance
    New car
    Comfortable to drive
    Low price
    Car 2 reputations:
    Bad for business
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.