What is an inner class and anonymous classes in Java?

What is an inner class and anonymous classes in Java


Inner Class:
An Inner class is a class that present inside a class is called inner class. Inner classes increase the complexity of code and should only used only if absolutely necessary.

Example:

class X {

   int x;

   public void func1() {

}



//Inner class



     class Y {

           public void func2() {

               // can access the instance variables of the parent

                  x=10;

                          }

      }// Y class

}//
X classy





Anonymous Class:
Anonymous class is an inner class can be declared without naming it. An anonymous class has a ability to declared and initiated a class at the same time.

Example:

public class Main {

  public static void main(String[] args) {

    Test b = new Test() {

      public void func() {

        System.out.println("This is it!");

      }

    };

    b.func();

  }
  interface Test{

    void func();

  }

}

Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 comments:

Post a Comment