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.
Explanation
Nested enums are essentially static nested classes. They do not belong to instances of the outer class.
Regardless of how many persons you create, you will always only have a single enum Gender floating around, thats it.
Same goes for its values, there are only 3 values of this enum - regardless of how many persons you create.
Inner classes
However, even if you have an inner (non-static) class, such as
class A {
class B { ... }
...
}
You will only have a single class B in memory (as you worded it). There is essentially always just a single class.
Now, when you create instances of B, you will have to create them based on a previously created instance of A, since instances of B now belong to instances of A and can only exist within their context.
Therefore, they also share non-static properties of that particular A instance. You will often see that being used for Iterator implementations of data-structures.
Static nested vs decoupled
If you have a static nested class, such as
class A {
static class B { ... }
}
you might ask what the only real difference to actually fully decoupling them, as in
class A { ... }
class B { ... }
would be that the nesting makes clear that they somehow belong to each other, topic-wise. An example would be the Entry class in Map.
Notes on efficiency
You should actually stop bothering about efficiency on those minor things. Instead, think about readability for readers.
Efficiency, in the way you have in mind, is rarely ever a factor. And if, usually only in a very small spot in the whole code base (which is usually identified using a profiler).
So basically, unless you have a really good reason to not, always strive for the most readable and understandable solution.
Related
I have a singleton class containing a bunch of control data that needs to be kept synchronized with the rest of my application. As a result, there are many times which I want another class to be able to read the information but not modify it. Currently, this singleton class has many public variables. I don't want to use getter and setter functions because they are wordy and annoying. Also, there are a lot of variables.
If my singleton class is called ControlData, I could create a second create a second class called ImmutableControlData, where it has all the same members, but they are declared final. Then, when retrieving my singleton, I would return an ImmutableControlData, rather than a ControlData object. However, this means that I need to constantly maintain the ImmutableControlData class as well as the ControlData class (annoying...)
If I had const-pointers, I would just return a const-pointer to my ControlData object. What can I do in Java, instead?
Java does not have const correctness like C++.
You could make an interface that declares the methods to read the data, but not the methods to modify the data. Make the class that holds the data implement this interface. Methods elsewhere in your program that should only read the data, should accept the interface, not the class, as the parameter type. For example:
public interface ReadablePerson {
String getName();
}
public class Person implements ReadablePerson {
private String name;
#Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Elsewhere...
public void someMethod(ReadablePerson p) {
System.out.println(p.getName());
}
Ofcourse, in someMethod you could still subvert this by casting p to Person, but at least it requires some conscious effort (adding the cast), which should alert the programmer that (s)he is doing something (s)he shouldn't do.
An advantage of this solution is that you don't have to make a defensive copy of the data.
First: If your Class has so many members, you should try to split the class into littler ones. Maybe you can summerize some variables eg.
ControlflowVariables
StateVariables
If you want to restrict the access to the variables you have to use getter. IDE can create getters and setters for you. The access to variables are the same:
singletonClass.variable is not worst then singletonClass.getVariable()
If you want to restrict the access only at some points in your code then create a final copy of tha variable
final int variable = singletonClass.getInstance().variable;
Personally, I would not try to control access in this way. There is nothing you can to do to prevent bad programmers from misusing your class. Even in C++, they could use a simple const_cast to remove your "protection" and modify the singleton any way they like.
Instead, I would restructure the code to make it easy for others to do the right thing and hard for them to get it wrong. Segregate the interface for ControlData into two separate interfaces: one for reading the object and one for updating it. Then simply provide the two interfaces where they're needed.
I was going through some code and I saw this:
public class A {
public A(SomeObject obj) {
//Do something
}
//Some stuff
public static class B {
//Some other stuff
}
}
I was wondering since even the inner class is public why have it as nested and not a separate class?
Also, can I do this here: new A.B(SomeObject) ? I feel this defeats the purpose of a static class but I saw this implementation as well so wanted to know.
I was wondering since even the inner class is public why have it as nested and not a separate class?
That's really a matter to ask whoever wrote the class. It can allow the outer class to act as a "mini-namespace" though - if the nested class is only useful in the context of the outer class, it seems reasonable. It indicates deliberate tight coupling between the two classes. I most often see this in the context of the builder pattern:
Foo foo = new Foo.Builder().setBar(10).build();
Here it makes sense to me to have Foo.Builder nested within Foo rather than as a peer class which would presumably be called FooBuilder.
Note that it also gives some visibility differences compared with just unrelated classes.
Also, can I do this here: new A.B(SomeObject) ?
No, because B doesn't have a constructor with a SomeObject parameter - only A does (in the example you've given).
I feel this defeats the purpose of a static class
You should try to work out exactly what you deem the purpose of a static class to be, and in what way this defeats that purpose. Currently that's too vague a statement to be realistically discussed.
You would have an inner class like this so
you can keep an class which only exists to support the outer class encapsulated.
you want to be able to access private members of the outer class or other nested classes.
you want a nested class with static fields (a weak reason I know ;)
you have a class with a very generic name like Lock or Sync which you wouldn't want to be mixed with other classes of the same name used by classes in the same package.
can I do this here: new A.B(SomeObject) ?
You can.
I feel this defeats the purpose of a static class
It takes getting used to but once you start you may have trouble not turning your entire program into one file.java ;)
1. A static inner class is known as Top-Level Class.
2. This static class has direct access to the Its Outer class Static method and variables.
3. You will need to initialize the static Inner class in this way from Outside...
A a = new A();
A.B b = new A.B();
4. new A.B(SomeObject) won't work... because you don't have a constructor with SomeObject as parameter...
5. But when the Inner class is Non-static, then it have implicit reference to the Outer class.
6. The outer and inner class can extends to different classes.
7. An interface's method can be implemented more than once in different or same ways, using Inner Class.
This pattern is used very often with the builder pattern. It not only makes clear the relation between a class and its builder, but also hides the ugly builder constructor/factory and makes builder more readable. For example in case you need your built object to have optional and not optional properties.
public class AnObject {
public static class AnObjectBuilder {
private AnObject anObject;
private AnObjectBuilder() {
}
private void newAnObjectWithMandatory(String someMandatoryField, ...) {
anObject = new AnObject(someMandatoryField,...)
}
public AnObjectBuilder withSomeOptionalField(String opt) {
...
}
}
public static AnObjectBuilder fooObject() {
return (new AnObjectBuilder()).newAnObjectWithMandatory("foo")
}
public static AnObjectBuilder barObject() {
return (new AnObjectBuilder()).newAnObjectWithMandatory("bar")
}
}
This way the client code have to call first the static method on the AnObjectBuilder class and then to use the optional builder methods:
AnObject.fooObject("foo").withSomeOptionalField("xxx").build(); without creating the builder object.
Pretty readable :)
I was wondering since even the inner class is public why have it as nested and not a separate class?
Have a look at this thread: Why strange naming convention of "AlertDialog.Builder" instead of "AlertDialogBuilder" in Android
Also, can I do this here: new A.B(SomeObject) ?
(Update) No, you can't do this, since B doesn't have a constructor that asks for SomeObject.
I hope this helps.
I was wondering since even the inner class is public why have it as
nested and not a separate class?
The simple reason it is allowed is packaging convenience.
Static nested class in Java, why?
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
yes, you can do new A.B(SomeObject). But you don't have to take my word for it, try it out.
I am reviewing the concept of inner classes in java. so far from what I've understood and applied java inner classes has a link or access to the methods and fields of its outer/ enclosing class.
My Question:
When should create or define an inner class?
are inner classes considered to be called as "Helper classes" ?
What are the indicators for you to make an inner class and what's their other purpose?
Inner classes are best for the purpose of logically grouping classes that are used in one-place. For example, if you want to create class which is used by ONLY enclosing class, then it doesn't make sense to create a separate file for that. Instead you can add it as "inner class"
As per java tutorial:
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one
place.
It increases encapsulation.
It can lead to more readable and maintainable code.
A classic use for an inner class is the implementation of an iterator inside a container (ArrayList, for example - look for class Itr). All the container wants to expose to the rest of the world is an Iterator. However, it has to create some concrete implementation of that iterator, possibly familiar with the internals of the container. Using an inner class hides the implementation, while keeping it close to the container's implementation. And being inner (i.e. non-static), it is bound to a specific instance of that container, which lets it access private container members.
There are a few types of inner classes - non-static nested class, local classes and anonymous classes. Each one has a somewhat different purpose, so when asking about an inner class, you should specify what kind are you talking about.
Assuming you're referring to non-static inner classes, I'd say the reason to use them is the same as using regular classes (namely abstraction and dividing code into logical units), but there's no reason to make this use of classes visible to the rest of the world. You can also make nested classes public, of course, in which case you'd make them nested instead of independent in order to express their tight relation with the outer class.
See the Java tutorial for the main reasons.
If by "helper class" you mean something for internal use only, then no, not necessarily. You might want to do something like
class Outer {
private static class Inner implements InterestingInterface {
// whatever
}
public InterestingInterface make_something_interesting() {
return new Inner();
}
}
Here, Inner is not a "helper class" in the sense that the outside world does get to see instances of it, but its implementation is entirely hidden -- the outside world only knows it gets some object that implements InterestingInterface.
As a general rule, objects should be designed for a single responsibility (Highly cohesive). In other words, any object designed well, should perform a single coherent task. This would be considered best practice for object orientated design.
Sometimes, however, a developer may design a class that requires a separate specialized class in order to work. This separate specialized class could be considered a helper class.
If the helper class is not used by any other class, then it would be considered a prime candidate as an inner class
As elicited by ncmathsadist above, an example of inner class use would be in the implementation of Event handlers.
For example, in designing a graphical user interface (GUI), a developer may have created a button that performs a particular task after the user presses it.
The button would need an event handler which listens for when that particular button is pressed.
In this case, creating the event handler for the button as an inner class would be best practice as the inner class would not be utilized anywhere else other than with the specific button within the GUI class.
One purpose of inner classes is to attach listeners. For example, suppose you have a JMenuItem. You can make it quit your app as shown in this code:
JMenuItem quitItem = new JMenuItem("Quit");
quitItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//cleanup code before exiting
System.exit(0);
}
});
You may also want a class to have access to outer class state variables which is entirely subservient to that class. For example, consider writing a simple color calculator. It might have a text area into which you type a hex code. When you hit enter, you want a JPanel to display the color. Here is a crude outline of what you might do.
public class ColorCalc extends JPanel implements Runnable
{
Color displayedColor;
JTextArea colorEnterArea;
public ColorCalc()
{
displayedColor = Color.white
colorEnterArea = new JTextArea();
}
public void run()
{
//build GUI here
}
public static void main(String[] args)
{
ColorCalc cc = new ColorCalc();
javax.swing.SwingUtilities.invokeLater(cc);
}
//subservient inner class with access to outer class state variable.
class ColorPanel extends JPanel
{
public void paintComponent(Graphics g)
{
g.setColor(displayedColor);
g.fillRect(0,0,getWidth(), getHeight());
}
}
}
This is a style question. Anything that can be done with an inner class can also be done as a as series of external classes. Inner classes are especially useful for classes that are lightweight or tightly bound to the enclosing class. For example, a comparator is frequently both these things. It needs intimate knowledge of the implementation of the class, and may only be a few lines long. It may be an ideal candidate as an internal class.
If you find that there is enough code which could be better done by class as class provides us to specify stats and
behavior with fields and methods and you don't want this class needs to be used outside of enclosing class. you should use inner class.
Here the inner class is hidden from the outside world.
Inner class can access the private member of enclosing class which provides us encapsulation.
Let me give example..
Suppose you want to set the gear to cycle and you have a business rule like there are only up to 6 gears.
So you can create Inner Class Cycle which would have a method to set the gear.
That method has some validation which are checked before setting gear.like the cycle is running...gear number is less than 6...
best example is event handling code uses inner classes(sometimes anonymous inner classes) to create events and listeners without creating separate Event Object and Event Listener classes for your event..
The inner class used for grouping classes logic, for example, if you have class B and this class used only at class A, So it is better to put class B as an inner class at class A, as this will give readability and reusability for your code.
Happy code :)
Adding from my personal notes, for future visitors:
Sources: https://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html
Lets say you have a type and its a class, called OuterClass, in a package called "com.custom.classes".
Then here is how you begin to need an inner class or static class:
Case 1:
you need to package a group of classes
but also kind of need certain global variables exposed to all these classes at that package level
you understand you can do no such things with packages but realise that you could achieve this with inheritance, where the parent class members can act as global variables that become available for all of its child class instances.
but you don't like the idea that you need to inherit the parent class and also that you need to instantiate the child class to access the global variables. Thats like asking to buy a coffee shop in order to have a coffee.
and so you realise that you can create an OuterClass with the static members and house all the classes in this OuterClass as inner class or static class as needed and lo! The OuterClass static members become available as global variables for these nested classes and you could even access them without instantiating them.
This code should explain better
public class InnerClassTester{
public static void main(String []args){
// without the need to instantiate any class
// static class without instantiation
System.out.println(OuterClass.NestedStaticClass1.incrGlobalNum()); // outputs 1
// static class instantiated
OuterClass.NestedStaticClass2 koolObj = new OuterClass.NestedStaticClass2();
// works with instantiation as well
System.out.println(koolObj.incrGlobalNum()); // outputs 2
// inner classes always need to be instantiated
// and they can only be instantiated from within an instance of outer class
// think of them as instance member of outer class and this would make sense
OuterClass.NestedInnerClass1 koolObj2 = new OuterClass().new NestedInnerClass1();
// works with inner classes as well
System.out.println(koolObj2.incrGlobalNum()); // outputs 3
}
}
class OuterClass{
// global variable thats only accessible for select classes (or nested classes)
// we also learn a purpose for private static fields
private static int privateGlobalValue = 0;
// classes to be grouped
// static class
public static class NestedStaticClass1{
// no need to instantiate this class to access/update the global value
public static int incrGlobalNum(){
return ++privateGlobalValue;
}
}
public static class NestedStaticClass2{
// instantiate and still manipulate the global value
public int incrGlobalNum(){
return ++privateGlobalValue;
}
}
// inner class
public class NestedInnerClass1{
// instantiate and still manipulate the global value
public int incrGlobalNum(){
return ++privateGlobalValue;
}
}
}
Does this remind you of closures in Javascript ? :)
Most applications of nested classes see it being applied on basis of design decisions. What that means is, every case of a nested class can be replaced with other designs.
But having said that, it is also true that we can also replace the inheritance pattern with composition pattern (and it is gaining momentum lately) although an inheritance pattern is definitely better when the dependencies between the classes is so much so that composing the dependencies entirely would be ugly.
Case 2:
you need to implement 2 interfaces, IShark and IMosquito, with the same signature, a public bite method, on the OuterClass.
but you want to display 2 different messages since a shark's bite is a tad different from that of a mosquito's.
however you know that's not possible since only one bite method can be implemented
you know you can create 2 different classes in the same package that implement either interfaces and also implement separate bite methods and have them composed in OuterClass.
but you wanted to get it done within OuterClass because it was your design decision to encapsulate the bite behaviour within it, maybe because there was a dependency on a private variable within the class.
soon you realise you can implement both the interfaces via private static inner classes and make it appear to the outside world as though it was composed.
Take a look at this code:
// no additional classes in the package
public class InterfaceTester{
public static void main(String []args){
// same class returns 2 instances - both compliant to
// either interfaces and yet different output
IShark shark = OuterClass.getSharkInstance();
System.out.println(shark.bite()); // outputs "Die fast bosedk!"
IMosquito mosquito = OuterClass.getMosquitoInstance();
System.out.println(mosquito.bite()); // outputs "Die slow bosedk!"
}
}
interface IShark{
public String bite();
}
interface IMosquito{
public String bite();
}
class OuterClass implements IShark{
// dependency of inner class on private variable
private static String dieSlow = "Die slow bosedk!";
private static String dieFast = "Die fast bosedk!";
private static OuterClass outerInst;
private static InnerClass innerInst;
// private constructor to stop regular instantiation
private OuterClass(){}
// get a shark !
public static IShark getSharkInstance(){
return outerInst != null ? outerInst : new OuterClass();
}
// get a mosquito !
public static IMosquito getMosquitoInstance(){
return innerInst != null ? innerInst : new InnerClass();
}
// an implementation of bite
public String bite(){
return dieFast;
}
// inner class that implements the second interface
private static class InnerClass implements IMosquito{
// different implementation of bite
public String bite(){
return dieSlow;
}
}
}
These kind of design decision cases are numerous and all of the answers above list several such cases. So it would not be wrong to think that this feature was introduced more as a new pattern than as a feature or functionality.
Conceptually inner classes can be used to represent types in the universe that would not exist without that parent type. In other words, with a language that allows inner classes, the types are all 'type definers'. A type can then be considered something that explicitly or implicitly defines new types.
For example, imagine we have a universe where "Food" can be applied to anything. Even itself. Food is a fundamental concept in our universe. We introduce a subclass of Food called Meat. Without that concept, there is no such thing as "Meat Eater". So we can (note 'can') define a nested type "Meat.Eater" (which could implement an IEater interface) and define animals as being a containment structure of lists of different IEaters.
Once we remove Meat from the universe, Meat Eater disappears to.
This same philosophy applies neatly to more abstract and technically useful arrangements such as Mementos in the Memento Design Pattern , a configuration object defined as a nested class, and other type-specific behaviours or structures.
It also increases encapsulation because inner classes can be declared private.
I would just consider that this is just a feature of language. I would not recommend to use it if we adopt OOD and obey the SOLID principle.
The Java tutorials that I read, like to use nested classes to demonstrate a concept, a feature or use.
This led me to initially implement a sample project I created just like that: Lots of nested classes in the main activity class.
It works, but now I got a monstrous monolithic .java file. I find it somewhat inconvenient and I now intend to break to multiple .java files/classes.
It occurred to me, however, that sometimes there may be reasons not to take classes out of their enclosing class.
If so, what are good reasons to keep a module large, considering modularity and ease of maintenance?
Are there cases in which it is impractical (or even impossible) to convert a nested class to a toplevel class? In other words, is there a case in which only a nested class could satisfy certain functionality?
It can be easier to read all the classes if they are in the same file. This is why this approach is good for example code.
However for real code, you should break your files/classes into manageable sizes. The longest class file in Java 6 is about 9000 lines long. I tend to keep classes shorter than this. ;)
a non-static nested class has an implicit reference to the creator instance of the enclosing class, and also it can access every member of the enclosing class (even private members). You lose this if you make the nested class top-level:
public class Outer {
private String s;
public void setS(String s) {
this.s = s;
}
public class Inner {
public String getOuterS() {
// This is legal only if Inner is
// non-static and nested in Outer
return s;
}
}
}
public class Main {
public static void main(String[] args) {
Outer o = new Outer();
o.setS("Hello world!!!");
// i now has access to every o member
Outer.Inner i = o.new Inner();
// Prints "Hello world!!!"
System.out.println(i.getOuterS());
}
}
Yes. Inner classes (non-static nested classes) may refer to instance variables of the containing class.
Also, nested classes may access private members of the containing class.
In addition to the benefit of closure (already pointed out in an other answer), nested classes also help you achieve multiple implementation inheritance (ref: Thinking in Java, page 369 - section "Why inner classes"?). As far I know, there is no other way to achieve it. So, if your nested class is helping you achieve multiple implementation inheritance, then it would not be possible for you to make the nested a top-level class.
Nested classes allow you to cleanly separate some functionality that belongs to the outer class and at the same time keep that functionality close to the outer class. In such cases, nested classes provide the best option from a design perspective and that alone can be the reason for not making it a top-level class (which can lead to class pollution in the main package).
I have inherited code which contains static nested classes as:
public class Foo {
// Foo fields and functions
// ...
private static class SGroup {
private static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>();
public SGroup(int id, String type) {
// ...
}
}
}
From reading SO (e.g. Java inner class and static nested class) I believe that this is equivalent to two separate classes in two separate files:
public class Foo {
// Foo fields and functions
// ...
}
and
public class SGroup {
static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>();
public SGroup(int id, String type) {
// ...
}
}
If this is correct is there any advantage to maintaining the static nested class structure or should I refactor?
It depends on what the class is used for. If it's coupled to the outer class, for example, just like Map.Entry, just leave it in. However, if it makes sense to use the class without its enclosing type, you may as well promote it to a top level class.
Jorn statement is correct and it's usually manifests itself as the following rule of thumb:
Nested classes should be made private, Meaning that the hold auxiliary logic for the hosting class and nothing more. If you cant make them private- thet probably should not be nested.
The exception is when you define a nested class to allow easy access to the state of the hosting class, in that case you should consider simply merging both classes to increase cohesion.
It is not improper to say that "static nested classes" are not nested classes at all. It is convenient to discuss static nested classes in the context of inner classes because the way they are declared in code is similar and also because a static nested class still has to be named with the enclosing class as a context.
However, here is an important thing to keep in mind about static nested classes: from the point of view of the compiler and the JVM, static nested classes are top level classes. In fact, the compiler implements them logically at compile time as top level classes (at least it used to; I think it still does).
Why, then, should anyone ever use static nested classes? Why not just write top level classes all the time?
For me, static nested classes provide a convenient mechanism for logically grouping closely related classes in a manner that keeps my project hierarchy nice and tidy. For example, say that I have a database with the following tables: Clients, Encounters, and Services. I -could- model these tables with separate top-level classes and it would work fine, but since these tables are all in the same database and relate to the same data, I find it convenient to model these as:
class DB {
static class Client {
...
}
static class Encounter {
...
}
static class Service {
...
}
}
To use an instance of one of the models:
DB.Encounter enc = new DB.Encounter();
In my view, this makes code more readable since it is immediately clear in the code that the object that is being created derives from one of my database models. It also keeps the class definitions for the models linked under a common heading which I also think helps make projects simpler to understand.
But from the point of view of the JVM (and the compiler, which implements them as top level classes anyway [just as it also gives "anonymous" inner classes names at compile time]), these objects are instantiated from top level classes. Making them does not depend on any instance of any object, nor can objects instantiated from a static nested class access any private members of the enclosing class.
I like static inner classes as they provide loose coupling from the enclosing class (no access to private members of the enclosing class) static inner classes are also easy to promote to top level (because of the loose coupling attribute).
There is a simple rule of the thumb when to promote them:
If another class (other than the enclosing) needs to reference \ use the inner class.