Java - Anonymous Classes
Java - Anonymous Classes
Learn Java in-depth with real-world projects through our Java certification course. Enroll and
become a certified expert to boost your career.
Syntax
The syntax of anonymous nested class is as follows −
new(argument-list){
// Anonymous class body
}
Open Compiler
package com.tutorialspoint;
class Car {
public void engineType() {
System.out.println("Turbo Engine");
}
}
public class Tester {
public static void main(String args[]) {
Car c1 = new Car();
c1.engineType();
Car c2 = new Car() {
@Override
public void engineType() {
System.out.println("V2 Engine");
}
};
c2.engineType();
}
}
Output
If you compile and execute the above program, you will get the following result −
Turbo Engine
V2 Engine
Open Compiler
package com.tutorialspoint;
interface Software {
public void develop();
}
public class Tester {
public static void main(String args[]) {
Software s = new Software() {
@Override
public void develop() {
System.out.println("Software Developed in Java");
}
};
s.develop();
System.out.println(s.getClass().getName());
}
}
Output
If you compile and execute the above program, you will get the following result −
Open Compiler
package com.tutorialspoint;
Output
If you compile and execute the above program, you will get the following result −
Turbo Engine