• Sunday, September 14, 2014

    Java - Local Class and Anonymous Class

    Local Class and Anonymous Class

    Local Class: If we declare an inner class within a method such class is known as local class.
    Use it if you need to create more than one instance of a class and access its constructor, or introduce a new, named type.
    Example:



    public class A
    {
    void fun()
    {
    class MyInnerClass
    {
    System.out.println("This is my Inner class");
    }
    }
    }

    Anonymous Class: The class which declared in a method without name is called as anonymous class.
    Use it if you need to declare fields or additional methods and need to use local class at once.

    Example (Syntax):

    HelloWorld College = new HelloWorld()
    {
    String collegeName = "ABC College";
    public void sayName()
    {
    System.out.println("College Name: " + collegeName);
    }
    };


    Note: HelloWorld is a interface which already defined and college is anonymous class.

    Syed Masoom Rizvi

    Author & Editor

    Hi, This is Syed Masoom Rizvi, who is continue exploring the world of programming ,programming and programming... :)

    0 comments:

    Post a Comment