Object Oriented Programming

Anonymous Class in Java

Anonymous classes are used to declare and instantiate a class all at once.


Syntax
className objectName = new className() {
    //class members
}

Notes

Typically, this is used to make code more concise.


Example
//assuming there is a car class already

Car mercedes = new Car() {
    private String origin = "Germany";
    
    public void sayOrigin() {
        System.out.println(origin);
    }
}

See Also
Documentation

Java Tutorial - Anonymous Class

Add to Slack

< Abstract Methods and Classes   |   Declaring an Exception >

© 2019 SyntaxDB. All Rights Reserved.