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
Answer from Jabir on Stack OverflowVideos
Please correct me if I am wrong, and explain where my understanding is incomplete.
From what I've read both static and final are keywords. If you make a variable or method static, it would only be accessed by the class itself and not by an instance of the class (object). A static class would be useful if it was nested inside another class and you didn't want an instance of the outer class to access the inner class.
If you make a variable final, then it is initialized once and not changed. A final class can't be subclassed, and a final method can't be overwritten. If a variable is static final, then it cannot be changed and it can only be accessed by the class itself and not an object of the class.
People use static all the time, but why is it useful to limit the access of a method or variable to the class itself and not any instances of it?
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
The static keyword can be used in 4 scenarios
- static variables
- static methods
- static blocks of code
- static nested class
Let's look at static variables and static methods first.
Static variable
- It is a variable which belongs to the class and not to object (instance).
- Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
- A single copy to be shared by all instances of the class.
- A static variable can be accessed directly by the class name and doesn’t need any object.
- Syntax:
Class.variable
Static method
- It is a method which belongs to the class and not to the object (instance).
- A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
- A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
- A static method can be accessed directly by the class name and doesn’t need any object.
- Syntax:
Class.methodName() - A static method cannot refer to
thisorsuperkeywords in anyway.
Static class
Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
Side note:
main method is
staticsince it must be be accessible for an application to run before any instantiation takes place.
final keyword is used in several different contexts to define an entity which cannot later be changed.
A
finalclass cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes arefinal, for examplejava.lang.Systemandjava.lang.String. All methods in afinalclass are implicitlyfinal.A
finalmethod can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.A
finalvariable can only be initialized once, either via an initializer or an assignment statement.
It does not need to be initialized at the point of declaration, this is called ablank finalvariable, but in this case:- A
blank finalinstance variable must be assigned at every constructor of its class. - A
blank finalstatic variable must be assigned in a static initializer in its class.
- A
Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
final - The value assigned to the variable cannot be changed.
static - Even in different class instances, compiler will allocate the same memory location to the variable which it had assigned no matter how many instances of that class. The value can be changed.
My question is: Why is the final keyword not allocating the same memory location to the variable, if the value cannot change?
Let us have different instances of a class and still we will have the same value in the variable as it has been declared as final.
Why do we need to write static final then, it could have been done via final only, am I missing on thinking some cases?
If someone can please clarify?
final indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.
Use public final static String when you want to create a String that:
- belongs to the class (
static: no instance necessary to use it). - won't change (
final), for instance when you want to define aStringconstant that will be available to all instances of the class, and to other objects using the class. - will be a publicly accessible part of the interface that the class shows the world.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT))
Similarly:
public static final int ERROR_CODE = 127;
It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.
Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.
Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
Finally note that final will only make truly constant values out of primitive types, String which is immutable, or other immutable types. Applying final to an object (for instance a HashMap) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.
- Static means..You can use it without instantiate of the class or using any object.
final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:
public class StringTest { static final String str = "Hello"; public static void main(String args[]) { // str = "world"; // gives error System.out.println(str); // called without the help of an object System.out.println(StringTest.str);// called with class name } }
Thanks
Static methods cannot be overridden but they can be hidden. The ts() method of B is not overriding(not subject to polymorphism) the ts() of A but it will hide it. If you call ts() in B (NOT A.ts() or B.ts() ... just ts()), the one of B will be called and not A. Since this is not subjected to polymorphism, the call ts() in A will never be redirected to the one in B.
The keyword final will disable the method from being hidden. So they cannot be hidden and an attempt to do so will result in a compiler error.
static methods cannot be overriden
This is not exactly true. The example code really means that the method ts in B hides the method ts in A. So its not exactly overriding. Over on Javaranch there is a nice explanation.