In general, are there any benefits in declaring a private class as static?
In what cases would I want to use one of the following over the other?
private static class Foo { ... }
vs
private class Foo { ... }
Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods.
If a method doesn't use any instance data in the class, it should be static. That way it's clear that it's independent of the instances, and that you don't have to create an instance to call it. Any performance differences should not be a concern.
A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name. It can access static data members of the outer class, including private.
Yes, we can have private methods or private static methods in an interface in Java 9. We can use these methods to remove the code redundancy. Private methods can be useful or accessible only within that interface only. We can't access or inherit private methods from one interface to another interface or class.
I think this is a good starting point: http://java67.blogspot.fi/2012/10/nested-class-java-static-vs-non-static-inner.html
1) Nested static class doesn't need reference of Outer class but non static nested class or Inner class requires Outer class reference. You can not create instance of Inner class without creating instance of Outer class. This is by far most important thing to consider while making a nested class static or non static.
2) static class is actually static member of class and can be used in static context e.g. static method or static block of Outer class.
3) Another difference between static and non static nested class is that you can not access non static members e.g. method and field into nested static class directly. If you do you will get error like "non static member can not be used in static context". While Inner class can access both static and non static member of Outer class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With