Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I want to make my private class static?

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 {     ... } 
like image 719
His Avatar asked Jun 03 '11 04:06

His


People also ask

When should a class be made static?

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.

Should I make a private method static?

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.

Can we have private static class?

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.

Why we use private static method in Java?

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.


1 Answers

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.

like image 148
Esko Piirainen Avatar answered Oct 11 '22 19:10

Esko Piirainen