+ 2

Help with anonymous classes [Java]

I don't undertand the coding couch to anonymous classes. when the second object is created: it doesn't end with semi-colon insted there is a { why??? public class Main { public static void main(String[] args) { Purchase customer = new Purchase(); Purchase specialCustomer = new Purchase(){ //I don't get the following part public int totalAmount(int price) { return price - (price*20)/100; } }; System.out.println(customer.totalAmount(1000)); System.out.println(specialCustomer.totalAmount(100000)); } } class Purchase { int price; public int totalAmount(int price) { return price - (price*10)/100; } }

11th Jan 2023, 1:37 PM
Darius
2 Answers
+ 2
An anonymous class is a special type of class that has no name. It is declared and instantiated in the same statement, and it can be used to create an instance of a class without having to define a new class. In the example code you provided, an anonymous class is being used to create a special purchase instance with a different totalAmount method. The code block after the declaration of the specialCustomer object is the anonymous class, which defines the new totalAmount method. The code block ends with a closing brace '}' instead of a semicolon to indicate that it is a code block, rather than just an ordinary object declaration.
11th Jan 2023, 9:18 PM
Aditya Dixit