class
Anonymous inner class constructor
This is an example of how to use an anonymous inner class. We have set an example following the above steps:
- We have created an abstract class,
Abs
that has a constructor and an abstract method. - We have also created another class,
InnerClassConst
, that has astatic
method,getAbs(int i)
, that returns a newAbs
, for a given int value, where it overrides thef()
method ofAbs
in order to print a message. - When calling a new Abs instance, calling
getAbs(int i)
method ofInnerClassConst
, it calls the overriden method in theAbs
constructor ofInnerClassConst
,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; abstract class Abs { public Abs(int i) { System.out.println("Abs constructor, i = " + i); } public abstract void f(); } public class InnerclassConst { public static Abs getAbs(int i) { return new Abs(i) { { System.out.println("Inside instance initializer"); } @Override public void f() { System.out.println("In anonymous f()"); } }; } public static void main(String[] args) { Abs a = getAbs(47); a.f(); } }
Output:
Abs constructor, i = 47
Inside instance initializer
In anonymous f()
This was an example of an anonymous inner class in Java.