Anonymous class declared as implementing interface and extending class

Can anonymous class declared as implementing interface and extending class

Answer: An anonymous class can either implement exactly one interface or extend one class. Example below:

public class AnonymousExample extends AnonymousClassTest {

    public static void main(String[] args) {
	AnonymousExample testInterface = new AnonymousExample();
	testInterface.testInterface2.methodTest();

	testInterface.anonymousClassTest.test();

    }

    //Here testInterface2 is an object of TestInterface which implements
    // TestInterface 
    TestInterface testInterface2 = new TestInterface() {

	@Override
	public void methodTest() {
	    System.out.println("Anonymous inner Type using interface");

	}
    };

    // anonymousClassTest is an object of AnonymousClassTest which extends
    // AnonymousClassTest
    AnonymousClassTest anonymousClassTest = new AnonymousClassTest() {
	public void test() {
	    System.out.println("Anonymous inner Type using class");
	}
    };

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *