Java Anonymous Class
# Java Anonymous Class\\\\n\\\\n[ Java Objects and Classes](#)\\\\n\\\\nIn Java, you can implement a class that contains another class, and instantiate it directly without providing any class name.\\\\n\\\\nIt is mainly used when we need to create an object to perform a specific task, which can make the code more concise.\\\\n\\\\nAnonymous classes are classes that cannot have names, they cannot be referenced, and can only be declared at the time of creation using the **new** statement.\\\\n\\\\nAnonymous class syntax format:\\\\n\\\\n```java\\\\nclass outerClass {\\\\n // Define an anonymous class\\\\n object1 = new Type(parameterList) {\\\\n // Anonymous class code\\\\n };\\\\n}\\\\n\\\\nThe above code creates an anonymous class object object1. Anonymous classes are defined in expression form, so they end with a semicolon `;`.\\\\n\\\\nAnonymous classes usually inherit from a parent class or implement an interface.\\\\n\\\\n!(#)\\\\n\\\\n### Anonymous Class Inheriting a Parent Class\\\\n\\\\nIn the following example, the Polygon class is created, which has only one method `display()`. The AnonymousDemo class inherits from the Polygon class and overrides the `display()` method of the Polygon class:\\\\n\\\\n## Example\\\\n\\\\n```java\\\\nclass Polygon{\\\\n\\\\n public void display(){\\\\n\\\\n System.out.println("in Polygon ClassInside");\\\\n\\\\n }\\\\n\\\\n}\\\\n\\\\nclass AnonymousDemo {\\\\n\\\\n public void createClass(){\\\\n\\\\n // The created anonymous class inherits from the Polygon class\\\\n\\\\n Polygon p1 = new Polygon(){\\\\n\\\\n public void display(){\\\\n\\\\n System.out.println("inAnonymous Class Insideγ");\\\\n\\\\n }\\\\n\\\\n };\\\\n\\\\n p1.display();\\\\n\\\\n }\\\\n\\\\n}\\\\n\\\\nclass Main {\\\\n\\\\n public static void main(String[] args){\\\\n\\\\n AnonymousDemo an = new AnonymousDemo();\\\\n\\\\n an.createClass();\\\\n\\\\n }\\\\n\\\\n}
YouTip