Java - What is the output Anonymous Base class

Question

What is the output of the following code.

abstract class AnonymousBase {
  abstract void hello();

  AnonymousBase(int i) {
    System.out.println(i);
  }
}

interface IAnony {
  void hello();
}

public class Main {
  public static void main(final String[] args) {
    new AnonymousBase(1) {
      String msg = (args.length == 1) ? args[0] : "nothing to say";

      @Override
      void hello() {
        System.out.println(msg);
      }
    }.hello();

    new IAnony() {
      public void hello() {
        System.out.println(2);
      }
    }.hello();
  }
}


Click to view the answer

1
nothing to say
2

Demo

abstract class AnonymousBase {
  abstract void hello();

  AnonymousBase(int i) {
    System.out.println(i);/*from   ww w. jav  a2  s.c  om*/
  }
}

interface IAnony {
  void hello();
}

public class Main {
  public static void main(final String[] args) {
    new AnonymousBase(1) {
      String msg = (args.length == 1) ? args[0] : "nothing to say";

      @Override
      void hello() {
        System.out.println(msg);
      }
    }.hello();

    new IAnony() {
      public void hello() {
        System.out.println(2);
      }
    }.hello();
  }
}

Related Topic