What are Unnamed Classes in Java 21?
In Java, unnamed modules and packages are a familiar concept. When we do not create a module-info.java class then the module is automatically assumed by the compiler. Similarly, if we do not add the package statement in the class in the root directory, the class just compiles and runs fine.
Same way, we can now create unnamed classes. Quite obviously, an unnamed class is a class without a name.
Example:
// Prior to Java 21
public class TestAConcept {
public static void main(String[] args) {
System.out.println(method());
}
static String method() {
//...
}
}
From Java 21, we can write the above class without the class declaration as follows. It removes the class declaration, public and static access modifiers etc. to have a cleaner class.
// In Java 21
void main(String[] args) {
System.out.println(method());
}
String method() {
//...
}
Save For Revision
Save For Revision
Bookmark this item, mark it difficult, or place it in a revision set.
Log in to save bookmarks, difficult questions, and revision sets.