Quite often I see people using inner enums, for example:
public class Person {
enum Gender {
MALE,
FEMALE,
OTHER
}
...
}
I am unsure how it works internally, so I am wondering whether there will be new instances of this enum class each time someone creates a new person, such as new Person()?
Will the inner enum keep costing more memory or will there only be a single one?
Follow up: Just have a quick test on the accepted answer in code editor(Java 11):
public class Person {
String name;
int Age;
Address address = new Address();//Usual way we see
public class Address {
String city;
String Country;
int number;
}
}
public class test {
public static void main(String[] args) {
var a = new Person.Address();//complains "innerclass.Person' is not an enclosing class, make Address Static"
var p = new Person();
var a1 = p.new Address();//correct syntax to create inner clas object outside its outer class
}
}
TBH, never expect such weird syntax of creating an inner class object. But considering we usually just use it in the outer class like how iterator is used in different data structure, it still makes sense that I feel strange about this. Finally, inner class object are created based on the actual needs and dependency on the outer class, so there is no efficiency issue
Regarding discussion between @Zabuzard and @user207421, both make a good point. user207421 points out that class is considered inner only when they are non-static. Enum and Record by nature are static: Oracle doc. It is good to learn from the root. But I do appreciate how Zabuzard explains everything in a way we can easily understand from scratch.