This question already has answers here:
What is the point of "final class" in Java?
(24 answers)
Closed 9 years ago.
In Java (and in Android), what's the use of static class and final class declarations?
My question is not about static instances but class declarations like,
static class StaticClass {
//variables and methods
}
and
final class FinalClass {
//variables and methods
}
Thanks,
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Final Classes
A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
http://docs.oracle.com/javase/tutorial/java/IandI/final.html
final classes will restrict for further extends (Inherit).
You can not use static keyword on outer class,static is permitted only to inner classes Static classes
You make a class final so it can not be extended. Usually it makes sense if you'are creating a library (or working on a part of a big project), so your clients are not able to extend the class and modify the existing behavior. In your own program there's little reason to make a class final unless it's a big program and you can inadvertently forget things.
Static inner classes are for things that logically belongs to an outer (containing) class but which have no dependencies on the state of the outer class. For example you can have a Parser class and an inner Parser.Listener class. Normally if you decide to have an inner class try, first, to make it static, if possible, to simplify things.
You could do without both final and static inner classes then with experience you will find use for them.
other class can not extends the final class exmple String is final class so you cannot extends this class.
You cannot have a 'top-level' class declared static. You can only have an inner class with the modifier 'static'.
static inner class only access the static member of the outer class
if you make a class as final then it can not be inherited. Generally top level class can not be made static however inner class can be made as static and Nested static class doesn’t need reference of Outer class
static and final class in java
you can't mark a class static ?
yes, if it is nested class
no, if it is normal class.
if you mark a nested class static it will work as fully flagged class just use a classname.staticClassNmae to access it.
if you mark a class final , it can't be inherited , a good example of this String class in java.
Related
This question already has answers here:
Why can outer Java classes access inner class private members?
(10 answers)
Closed 2 years ago.
Could someone please explain how private members of a static nested class are accessible outside the class?
class Main {
static class Inner{
private static int calc= 10;
}
public static void main(String args[]){
System.out.println("calc is "+Main.Inner.calc);
}
}
The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class.
The inner class is (for purposes of access control) considered to be part of the containing class. This means full access to all privates.
The way this is implemented is using synthetic package-protected methods: The inner class will be compiled to a separate class in the same package. The JVM does not support this level of isolation directly, so that at the bytecode-level will have package-protected methods that the outer class uses to get to the private methods/fields.
If you like to hide the private members of your inner class, you may define an Interface with the public members and create an anonymous inner class that implements this interface.
This question already has answers here:
Java inner class and static nested class
(28 answers)
Closed 7 years ago.
I came across this in java, I know its a static nested class but why create an instance of 'static'. Isn't the whole idea of 'static' to use it without an instance? I understand the concept of inner classes, but why (and frankly how is it possible to) create an 'instance' of a 'static' member at all ?
Why this:
1- OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
2- nestedObject.aNestedClassMethod();
and not this:
1- OuterClass outerInstance=new OuterClass();
2- outerInstance.StaticNestedClass.aNestedClassMethod();
Use on inner classes, the keyword static indicates that you can access the inner class without an instance of the outer class.
For example:
public class Outer {
public static class Inner {
/* Code here. */
}
}
with this construction, you can create an instance of the inner class by using this code:
new Outer.Inner()
If the inner class would not be static, but also like this:
public class Outer {
public class Inner {
/* Code here. */
}
}
Then, you would have to create an instance of Outer in order to access Inner:
new Outer().new Inner()
Don't think of a static class as being a member of its enclosing class. It's a class of its own, totally separate. The only real distinction between it and a top-level class is that it has a slightly different name, and it can be private — which again doesn't affect its semantics, other than the fact that only the enclosing class knows about it.
So, if I have:
public class EnclosingClass {
public static class InnerClass {
}
}
Then anyone can come around and do:
EnclosingClass.InnerClass instance = new EnclosingClass.InnerClass();
See: exactly the same as a top-level class.
This is actually true of an inner class, too. There things are slightly more complicated, but basically the idea is that the inner class is still its own class, but it has a (mostly hidden) reference to the instance of the enclosing class that created it. I say "mostly" because it's possible to access that instance, via EnclosingClass.this. The java compiler also does some convenience plumbing for you, such that someFieldInTheEnclosingClass becomes EnclosingClass.this.someFieldInTheEnclosingClass. But don't let that shorthand fool you: the inner class is its own separate class, and its instance is its own separate instance; they're no different than a top-level class in that regard.
Thanks everyone who replied and commented. I have finally got the hang of it. I guess the answer was right in front of my eyes.
The reason behind calling a an inner static class 'static' is how its referenced and not how the class behaves. Since we don't need and instance of the OuterClass to create an instance of InnerClass and we simply use OuterClass name, rather than its object to instantiate the inner class.
Special thanks to Sleiman Jneidi, who posted the very first comment, the name static here "is" misleading.
1- OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Is there a difference between initialisation of a static nested class and top level class?I understand that static class doesnt require an enclosing class instance but what happens if there are multiple instances of the static nested class? Just like static variables are shared by class instances, will the instances of the static class be shared also?
Let me see if I understand your question correctly.
A class can declare nested classes.
If a class C1 declares a non-static inner class C2, then C2 has access to all of C1's fields and methods, regardless of their access modifiers.
C2 is, in fact, treated as a field: its declaration is loaded whenever a new instance of C1 is created. This means that non-static inner classes are rather more expensive than static ones, and should be avoided if not strictly necessary.
If a class C1 declares a static inner class C3, then C3 is shared across all instances of C1. It has access to all static methods and fields of C1, but not to non static ones - C3 is by definition not tied to a specific instance of C1, so there is nothing for it to have access to.
When you declare a static inner class, you're not saying anything about its instances. You're just telling the compiler that the class' definition is shared across all instances of the enclosing class. So, no, instances of the nested static class aren't shared automatically.
A static nested class does not required an instance of the enclosing class (as you point out) so there is nothing to share.
If you have a static variable then every instance of the class will hold a reference to the same static variable. Changes in one class will change the variable in all classes.
As a class is immutable at run time then this same logic doesn't carry through.
An instance of a static nested class is effectively the same as an instance of any other class.
The only way an instance would be shared would be if you had a static variable pointing to an instance of a static nested class. In this case it is the same as any other static variable.
As is pointed out the the tutorial the only real different between a static nested class and a top level class is that a static nested class can access private static members of it's enclosing class.
Every class is a singleton object of type Class.
A static inner class is the base case. It is the other, normal inner class, that also has an OuterClass.this pointer for its instance objects.
So as such, there is no difference in class initialisation of any class.
The nested class as you declared it as "static class" does not differ from another top level class like inner class does. Adding the static to it declaration you promote it to be separated from owner class that became only a namespace for it.
package org.stack.question
public class Top {
public static class Nested {
}
}
To create a instance of Nested class you must only do this
Object instance = new org.stack.question.Top.Nested();
From specification:
Nested classes that are not inner classes may declare static members
freely, in accordance with the usual rules of the Java programming
language. Member interfaces (§8.5) are implicitly static so they are
never considered to be inner classes.
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
{
...
}
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 i understand correctly, the question is for private class vs private static class. All the responses are generally about inner classes, that are not 100% applied to that question. So first things first:
From geeksforgeeks:
Nested class -> a class within another class
static nested class -> Nested classes that are declared static are called static nested classes
inner class -> An inner class is a non-static nested class.
As the accepted response says, static vs non-static nested classes differ on the way and possibility to access methods/fields outside the outer class. But in case of private classes B within class A, you dont have this issue, cause B is not accessible outside A anyway.
Now, from inside class A, for non-static fields/methods you can always refer to class B, either by saying new A.B() or just new B() and it doesnt matter (no compilation/runtime errors) if B is private class or private static class. In case of static fields/methods you need to use a private static class.
Moreover, if you want to access from inside B a non-static field of A, then you can't have B as private static class.
I generally prefer private static class, except when i cant use it like in the previous case, cause intellij will give warnings otherwise.
If you need access to the member variables/methods of the enclosing class, use the non-static form. If you don't, use the static form.
I would assume you are referring to inner classes.
I think the motivation would be coming from how you want to associate your inner class. If you want your inner class to be associated to a specific instance of its outer class, you'd use private class, otherwise, use private static class.
I found it useful in having a specific exception in a generic abstract class. I.e.:
public abstract class AbstractClass <T>
{
private void doSomethingOrThrowException() throws SpecificException
{
....
if ( ! successful)
{
throw new SpecificException();
}
}
private static class SpecificException extends Exception {}
}
If I were to leave out the static, the compiler would give me an error that states: The generic class AbstractClass<T>.SpecificException may not subclass java.lang.Throwable
static classes differ from ordinary classes only in that they can be accessed without their instances being created. so if you need some class to be accessable every time, use static
How do I declare a static class in java? eclipse wants me to remove "static" from the declaration.
static public class Constants {
First to answer your question:
Only a Nested class can be declared static. A top level class cannot declared be static.
Secondly, Inner class is a nested class that is not explicitly declared static. See the java language spec. So contrary to some answers here, Inner classes cannot be static
To quote an example from the spec:
class HasStatic{
static int j = 100;
}
class Outer{
class Inner extends HasStatic{
static final int x = 3; // ok - compile-time constant
static int y = 4; // compile-time error, an inner class
}
static class NestedButNotInner{
static int z = 5; // ok, not an inner class
}
interface NeverInner{} // interfaces are never inner
}
If by 'static' you mean 'can have only static members', there's no such thing in Java.
Inner classes (and only them) can be static, but that's a different concept. Inner static classes can still have instance members.
Eclipse complains correctly, your code won't compile as Top level class can't be declared as static.
You need to first understand what static class means.
static class :
Top level class can't be declared as static. Only Member and Nested top-level classes can be defined as static.
You declare member classes when you want to use variables and methods of the containing class without explicit delegation. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If you want to remove this restriction, you declare the member class a static class.When you declare a member class with a static modifier, it becomes a nested top-level class and can be used as a normal top-level class as explained above.
nested top-level class is a member classes with a static modifier. A nested top-level class is just like any other top-level class except that it is declared within another class or interface. Nested top-level classes are typically used as a convenient way to group related classes without creating a new package.
Also check when should we go for static class,variables and methods in java
As you have already been told from the other comments, classes cannot be declared static. However there are alternatives to this problem.
The most simple one is to precede all member variables and methods with the static modifier. This essentially does what you want.
A slightly more involved alternative is to make the class a singleton. This is a class in which through the use of a private constructor, and an instanceOf() method, or just an Enum, you can only have one instance of that class. Semantically and syntactically you treat that instance as an ordinary instance of whatever particular class you are making a singleton, but you can only have a single instance of that class, which you retrieve via SomeObject.instanceOf(), or in an Enum implementation, SomeObject.INSTANCE.
You would normally use Enums to implement this, minus the edge cases where you are extending another class.
For more complete information on singletons visit the link below.
Design Patterns in Java - Singleton
There is no direct equivalent of C# static classes in Java, but the closest thing in my opinion is an empty enum, which might seem weird at first, but makes sense the more you think about it. An enum in Java (unlike in C#) is essentially a set of singleton instances that all implement the same abstract base class and interfaces. The quickest and safest way to make a normal singleton in Java is like so:
enum Foo {
INSTANCE;
public Bar doSomething(Baz baz) {
return Bar.fromBaz(baz); // yadda yadda
}
}
So since we are dealing with sets of singletons, it make sense that we can have an empty set. And an empty set means there can be no instances. This is conceptually the same as a static class in C#.
enum MyUtilities {
;
static Bar doSomething(Baz baz) {
return Bar.fromBaz(baz); // yadda yadda
}
static final String SOME_CONSTANT = "QUX";
}
This is great because you won't lose test coverage because of hard to test private constructors in a final class, and the code is cleaner than a final class with an empty private constructor.
Now, if the static classes are meant to all work on a single Interface and you have control of that Interface, then you should implement the static methods on that Interface itself (something you can't do in C#).
All top level classes are implicitly static, meaning they can be accessed by everybody. So it makes sense only to make inner classes optionally static.